我有两个具有一对多关系的模型。我想在 Blade 中显示具有关系的数据。
店铺 table id | name | url
1 | NY | ny |
2 | CA | ca |
产品表 id | shop_id | slug
1 | 1 | ca
2 | 2 | wa
店铺.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]。
最佳答案
Try this:
public function products(){
return $this->hasMany('App\Product','shop_id','id');
}
关于php - Laravel - Eloquent 关系不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50231610/