Laravel - Eloquent 关系不正常
Laravel - Eloquent Relationship not working
我有两个模型有 One-to-Many 关系。我想显示关系在 blade.
中的数据
店铺Table
<strong>id |姓名 | url</strong>
1 |纽约 |纽约 |
2 |加州 |加州 |
产品Table
<strong>id | shop_id |鼻涕虫</strong>
1 | 1 |加州
2 | 2 |哇
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]) }}"
它 returns 属性 [shop_id] 在这个 collection 实例上不存在。
您不需要您刚刚建立的店铺关系
products = Product::where('shop_id',$shop->id)->get();
事实上你的函数没有return值,它有什么用?
您指定了错误的列:
public function shops()
{
return $this->belongsTo(Shop::class, 'shop_id');
}
Try this:
public function products(){
return $this->hasMany('App\Product','shop_id','id');
}
你的问题在这里:<a href="{{ route('view', [$url, $products->slug]) }}"
$products - this is collection. You need to do $products[0]->slug
或
@foreach($products as $product)
<a href="{{ route('view', [$url, $product->slug]) }}"
@endforeach
我有两个模型有 One-to-Many 关系。我想显示关系在 blade.
中的数据店铺Table
<strong>id |姓名 | url</strong>
1 |纽约 |纽约 |
2 |加州 |加州 |
产品Table
<strong>id | shop_id |鼻涕虫</strong>
1 | 1 |加州
2 | 2 |哇
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]) }}"
它 returns 属性 [shop_id] 在这个 collection 实例上不存在。
您不需要您刚刚建立的店铺关系
products = Product::where('shop_id',$shop->id)->get();
事实上你的函数没有return值,它有什么用?
您指定了错误的列:
public function shops()
{
return $this->belongsTo(Shop::class, 'shop_id');
}
Try this:
public function products(){
return $this->hasMany('App\Product','shop_id','id');
}
你的问题在这里:<a href="{{ route('view', [$url, $products->slug]) }}"
$products - this is collection. You need to do $products[0]->slug
或
@foreach($products as $product)
<a href="{{ route('view', [$url, $product->slug]) }}"
@endforeach