2017-01-04 2 views
1

laravelの雄弁な関係で遊んでください。 私はこれらの関係を持っています。複数の列との雄弁な関係の問い合わせ

注文:

id 
id_customer 

Order.php

public function orderDetails(){ 
    return $this->hasMany('App\OrderDetail', 'order_id'); 
} 

OrderDetail

id 
order_id 
product_id 
quantity 

OrderDetailモデル

public function product() 
{ 
    return $this->hasMany('App\Product', 'id', 'id'); 
} 

public function order(){ 
    return $this->belongsTo('App\Order', 'order_id', 'id'); 
} 

製品

dd'ed

id name price

DD( 'ORDERDETAILS' と(の$ this - > order->) - >を取得();

注文の詳細に商品のIDが含まれた注文と注文明細を取得できます。しかし、私はそれを表示することができるように製品の名前を得ることができるようにしたい。

どのようなクエリを実行するか、より良い方法で関係を定義しますか?

+0

だろう方法です?? !! – aimme

+0

製品には名前の列があります –

+1

正しく表示されるように編集しました。 –

答えて

3

使用nested eager loading

$this->order->with('orderDetails', 'orderDetails.product')->get(); 

関係がbelongsTo()はなく、hasMany()次のようになります。

public function product() 
{ 
    return $this->belongsTo('App\Product', 'product_id', 'id'); 
} 

また、あなたはここで多対多の関係を使用することができます。しかし、それが適切な場合のみ。

+0

これを試したところ、orderDetailsは空の配列になりました。 –

+1

関係を変更しましたか? $ order-> order-> with( 'orderDetails'、 'orderDetails.product') - > get(); 'はあなたのために働きますか? –

+0

'$ this-> order-> with( 'orderDetails') - > get();'は実際に私に製品のIDを含む詳細を与えます。しかし、製品の名前を取得する方法がわかりません –

2

この質問を参考にしていただいた皆様のために、あなたがリレーションシップ提案を依頼したように、ここに私はこれと私の意見を達成する方法があります。

その実際の製品は多くの注文に属し、注文は多くの製品に属します。その注文の詳細がピボットであることがわかります。必要に応じてモデルを作成することもできます。

productsテーブル

id 
customer_id 

Product.php

public function orders() 
{ 
    return $this->belongsToMany(Order::class, 'order_details', 'order_id', 'product_id')->withPivot('quantity'); 
} 

ordersテーブル

id 
name 
price 

Order.php

public function products() 
{ 
    return $this->belongsToMany(Product::class, 'order_details', 'product_id', 'order_id')->withPivot('quantity'); 
} 

OrderDetailは、テーブルへの参照がないため作成しないことがあります。 だけorder_detailsテーブル

id 
order_id 
product_id 
quantity 

が、私はOrderDetailモデルを作成した場合、ここでそれは私が名前の欄を参照してくださいいけない、名前がない

public function products() 
{ 
    return $this->hasMany(Product::class, 'product_id'); 
} 

public function orders() 
{ 
    return $this->hasMany(Order::class, 'order_id'); 
}