Laravel - Eloquent关系不起作用

4
我有两个具有一对多关系的模型。我想在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]。

4个回答

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

2
你不需要商店的关系,只需执行即可。
products = Product::where('shop_id',$shop->id)->get();

事实上,您的函数并不返回值,它有什么用处呢?

没有起作用。我使用这个来获取与产品表中的“id”匹配的Shop表中的“shop_id”的**商店网址**。 - universal
你到底想要做什么? - madalinivascu
我想将“商店网址”前缀添加到每个与之相关的“产品别名”,以匹配相应的商店关系。例如,对于产品编号1,我希望将其URL显示为domain.com/ny/ca,对于产品2:domain.com/ca/wa。 - universal
实际上,出于编程的考虑,最好定义关系。 - Mladen Janjetovic

0
您指定了错误的列:
public function shops()
{
    return $this->belongsTo(Shop::class, 'shop_id');
}

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接