我有两个具有一对多关系的模型。我想在Blade中显示带有关系的数据。
商店表
id | name | url
1 | 纽约 | ny |
2 | 加利福尼亚州 | ca |
产品表
id | shop_id | slug
1 | 1 | ca
2 | 2 | wa
Shop.php
public function products()
{
return $this->hasMany(Product::class, 'shop_id');
}
产品型号
public function shops()
{
return $this->belongsTo(Shop::class, 'id');
}
Controller.php
public function category($slug)
{
$shop = Shop::where('url', $slug)->firstorfail();
$products = Product::with(['shops'])->where(['shop_id' => $shop->id)->get();
$url = Shop::where('id', $products->shop_id)->pluck('url');
}
路由
Route::get('/{url}/{slug}', 'Controller@category')->name('view')->where('slug', '[\w\d\-]+(.*)');
查看
<a href="{{ route('view', [$url, $products->slug]) }}"
它返回该集合实例上不存在属性[shop_id]。
商店网址
**。 - universal