2017-02-14 70 views
0

我有三个表,我想在获取结果时使用数据透视表数据。与数据透视表的关系

这些表是产品,存储,store_products,cart_items和他们的田地都低于:

  • 产品(ID,名称,价格)

  • 店(ID,姓名等)

  • store_products(STORE_ID,PRODUCT_ID,store_price,store_slug)

  • cart_items(ID,USER_ID,PRODUCT_ID,S tore_id,数量)

我CartItem模型就像

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

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

} 

当我打电话CartItem::with('product')->get(),我想它与数据透视表"store_products"匹配cart_items.store_id and cart_items.product_id返回产品数据(from product table and store_price, store_slug from store_products)

如何通过我的CartItem模型创建此关系?如果可能,只需使用Eloquent ORM函数而不是查询构建器或原始查询。

回答

0

在产品型号增加,

public function stores(){ 
    return $this->belongsToMany(Store::class)->withPivot('store_price', 'store_slug'); 
} 

在存储模型添加,

public function products(){ 
    return $this->belongsToMany(Products::class)->withPivot('store_price', 'store_slug'); 
} 

然后调用,

CartItem::with(['product.stores'])->get(); 

更多解释请阅读这篇文章:

http://laraveldaily.com/pivot-tables-and-many-to-many-relationships/

+0

你好,谢谢你的回答,但是这并没有返回正确的结果。这包括产品数据到CartItem,其中所有商店都位于数据透视表中。我想要做的就是获得每个CartItem行中定义的特定store_id的数据透视结果 –

+0

试试这个'CartItem :: with(['store.products']) - > get();' –