2017-02-14 15 views
0

私は3つのテーブルを持っており、結果を得るにはピボットテーブルのデータを使用したいと思います。ピボットテーブルとの関係

これらのテーブルには、商品、店舗、store_products、cart_itemsであり、そのフィールドは以下の通りです:

  • 製品(ID、名前、価格)

  • ストア(ID、名前など)

  • store_products(STORE_ID、PRODUCT_ID、store_price、store_slug)

  • cart_items(ID、USER_ID、PRODUCT_ID、S私はCartItem::with('product')->get()を呼び出すときtore_id、量)

マイCartItemモデルは

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

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

} 

ようなもので、私はそれがピボットテーブル"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'); 
} 

を追加し、その後呼び出し、より詳細な説明については

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

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

を追加するには、この記事をお読みください。

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

+0

お返事ありがとうございますが、正しい結果が返されません。これには、ピボットテーブルにすべての店舗があるCartItemへの商品データが含まれています。私がしたいのは、各CartItem行で定義されている特定のstore_idのピボット結果を取得することです。 –

+0

これを試してみましょう。 'CartItem :: with(['store.products']) - > get();' –

関連する問題