【发布时间】:2018-05-30 01:43:01
【问题描述】:
我正在使用 Laravel 框架进行电子商务项目。我有一个产品表、一个风味表和一个风味产品表(我相信这被称为数据透视表)。我有一个 Product 模型和一个 Flavor 模型(根据我的阅读,没有必要为数据透视表创建模型)。
在 Product 模型中我定义了以下关系:
public function flavors()
{
return $this->belongsToMany('App\Flavor');
}
在 Flavor 模型中我定义了以下关系:
public function products()
{
return $this->belongsToMany('App\Product');
}
现在,在我的产品控制器中,我尝试了以下操作:
$flavors = Product::select('id')->with('flavors')->get();
它被发送到适用的视图 (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 & 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');
【问题讨论】:
-
与哪个产品相关联?
-
当前显示的那个。
-
嗯,您可以分享您检索该产品并显示它的代码吗?您如何知道要检索哪些产品的风味?现在,您的代码会获取所有产品。
-
我希望我在编辑中添加的附加信息是您正在寻找的。根据产品的唯一 slug 检索产品。
-
是的,这让你更清楚你想要什么。将为您解决问题。
标签: mysql laravel laravel-5 eloquent has-and-belongs-to-many