Laravel 5:通过几个表格的关系

时间:2018-04-12 09:25:06

标签: laravel-5 database-relations

我有以下型号:商家,商品和商店:

商户:

class Merchant extends Model
{
    public function products() {
        return $this->hasMany('App\Product');
    }
}

产品:

class Product extends Model
{
    public function merchants() {
        return $this->belongsTo('App\Merchant');
    }


    public function stores() {
        return $this->belongsTo('App\Store');
    }
}

商店:

class Store extends Model
{
    public function products() {
        return $this->hasMany('App\Product');
    }
}

在我的MerchantController中,我有以下方法show()

public function show() {

    $merchants = Merchant::selectRaw('merchants.*, REPLACE(abstract, \'[[name]]\', name) AS abstract')
    ->with('products')
    ->where('active', 'yes')
    ->Paginate(10);

    dd($merchants);

    //return view('merchants', compact('merchants'));
}

我如何访问商店,几个产品都在?我试过->with(['products', 'stores'])并收到错误消息: Call to undefined relationship [stores] on model [App\Merchant].

我可以做些什么来解决我的问题?

1 个答案:

答案 0 :(得分:0)

使用laravel' hasManyThrough关系

Merchant模型中 添加这种关系

public function stores()
{
    return $this->hasManyThrough(Store::class, Product::class);
}