Laravel - 雄辩的关系不起作用

时间:2018-05-08 10:39:05

标签: php laravel orm eloquent relational-database

我有两个具有一对多关系的模型。我想在刀片中显示关系数据。

购物表

id | name | url 1 | NY | ny | 2 | CA | 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]。

4 个答案:

答案 0 :(得分:2)

你不需要你刚做的商店关系

products = Product::where('shop_id',$shop->id)->get();

实际上你的函数没有返回一个值,它用于什么?

答案 1 :(得分:0)

您指定了错误的列:

public function shops()
{
    return $this->belongsTo(Shop::class, 'shop_id');
}

答案 2 :(得分:0)

Try this:  
  public function products(){
        return $this->hasMany('App\Product','shop_id','id');
    }

答案 3 :(得分:0)

您的问题在这里:<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