mysql - Eloquent belongsToMany 和三表(包括 Pivot)

标签 mysql laravel laravel-5 eloquent has-and-belongs-to-many

enter image description here

我正在使用 Laravel 框架开发一个电子商务项目。我有一个产品表、一个口味表和一个 flavor_product 表(我相信这被称为数据透视表)。我有一个 Product 模型和一个 Flavor 模型(据我所知,没有必要为数据透视表创建模型)。

在产品模型中,我定义了以下关系:

public function flavors()
{
    return $this->belongsToMany('App\Flavor');
}

在 Flavor 模型中,我定义了以下关系:

public function products()
{
    return $this->belongsToMany('App\Product');
}

现在,在我的产品 Controller 中,我尝试了以下操作:

$flavors = Product::select('id')->with('flavors')->get();

它被发送到适用的 View (product.blade.php)。

在 product.blade.php 我有以下内容:

@foreach ($flavors as $flavor)
  <select id="product-flavor" class="bs-select">
     <option value="{{ $flavor }}">{{ $flavor }}</option>
  </select>
@endforeach

那么,给我的是什么?好吧,它向我展示了以下内容:

{"id":1,"flavors":[{"id":1,"name":"Cake Batter","created_at":"2018-05-29 20:12:56","updated_at":"2018-05-29 20:12:56","pivot":{"product_id":1,"flavor_id":1}},{"id":2,"name":"Caramel Coffee","created_at":"2018-05-29 20:48:25","updated_at":"2018-05-29 20:48:25","pivot":{"product_id":1,"flavor_id":2}},{"id":3,"name":"Chocolate Milkshake","created_at":"2018-05-29 20:49:09","updated_at":"2018-05-29 20:49:09","pivot":{"product_id":1,"flavor_id":3}},{"id":4,"name":"Cookies &amp; Cream","created_at":"2018-05-29 20:49:50","updated_at":"2018-05-29 20:49:50","pivot":{"product_id":1,"flavor_id":4}},{"id":5,"name":"Vanilla Milkshake","created_at":"2018-05-29 20:50:16","updated_at":"2018-05-29 20:50:16","pivot":{"product_id":1,"flavor_id":5}}]}

我绝对不想要所有这些。我只想通过数据透视表检索与该产品关联的口味名称。

我该如何处理?

编辑

以下代码在 ShopController.php 中(关于如何检索和显示产品):

/**
 * Display the specified resource.
 *
 * @param  string  $slug
 * @return \Illuminate\Http\Response
 */
public function show($slug)
{
    $product = Product::where('slug', $slug)->firstOrFail();
    $mightAlsoLike = Product::where('slug', '!=', $slug)->mightAlsoLike()->get();

    return view('product')->with([
        'product' => $product,
        'mightAlsoLike' => $mightAlsoLike,
    ]);
}

来自 web.php:

Route::get('/shop/{product}', 'ShopController@show')->name('shop.show');

最佳答案

你在这里所做的是告诉 Laravel 从所有产品中选择 id 并检索所有相关的口味。

Product::select('id') // <-- Will only select `id` attribute from the `products` table
    ->with('flavors') // <-- Will attach associated flavors to the product id
    ->get(); // <-- End the query (get all product ids and their flavours)

在您的情况下,您不想选择所有产品并且您已正确设置关系。所以你应该做的是在你的原始查询上调用 ->with('flavors') (在这种情况下实际上不需要,因为你不会遇到 n+1 问题,但仍然是很好的做法):

$product = Product::where('slug', $slug)->with('flavors')->firstOrFail();
$mightAlsoLike = Product::where('slug', '!=', $slug)->mightAlsoLike()->get();

return view('product')->with([
    'product' => $product,
    'mightAlsoLike' => $mightAlsoLike,
]);

然后在 View 中调用$product->flavors:

@foreach ($product->flavors as $flavor)
  <select id="product-flavor" class="bs-select">
     <option value="{{ $flavor }}">{{ $flavor }}</option>
  </select>
@endforeach

上面的 View 代码将按原样工作,而无需在查询中实际调用 ->with('flavors')->with(...) eager 加载关系并且在加载多个父级时显式调用是一种很好的做法,以避免 n+1 问题(性能!)。

但在您的情况下,您只显示 1 种产品的口味,因此显式调用它并没有真正的优势(除了更清晰的代码)。

编辑以解决评论:

<select id="product-flavor" class="bs-select">
@foreach ($product->flavors as $flavor)
    <option value="{{ $flavor->id }}">{{ $flavor->name }}</option>
@endforeach
</select>

您会看到多个选择,因为您在循环内打印整个选择,而不是只打印选项。

要显示当前 flavor 的任何属性,只需调用属性名称:例如 $flavor->name

关于mysql - Eloquent belongsToMany 和三表(包括 Pivot),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50595244/

相关文章:

Mysql子查询优化-count

mysql - 快速 mysql_query() 问题

php - Laravel 中的路由顺序很重要

laravel - 需要安装 League/flysystem-aws-s3-v3 联盟/flysystem ^2.0 但卡在 1.1.3 时出现问题

php - 如何从 Laravel 中的第二个表中获取相关数据?

Php Mysql 搜索问题

mysql 如何 COUNT() 可空字段 + IFNULL

Laravel 允许用户在满足条件时访问特定路由

php - 在 laravel 中从 routeserviceprovider 创建路由时中间件不工作

laravel-5 - 拉拉维尔 : change a raw query in a "query-builder" or "eloquent" one