mysql - Laravel Eloquent Relationship instead of Join on third table not related to parent -
i have orders
table , order_items
table related hasmany
, belongsto
respectively.
there products
table related order_items
hasmany
, belongsto
respectively.
what goal is, create orders
object includes products without using join
.
is possible, how relationships set make happen in eloquent?
ideally, have in with
cannot figure out how make work.
order model:
class order extends eloquent { public function orderitems() { return $this->hasmany('orderitem'); } }
orderitem model:
class orderitem extends eloquent { public function order() { return $this->belongsto('order'); } public function products() { return $this->belongsto('product'); } }
product model:
class product extends eloquent { public function orderitems() { return $this->hasmany('orderitem'); } }
query:
$order = order::with('user', 'orderitems', 'address') ->where('orders.id', $id) ->get() ->toarray();
you're looking belongstomany
relationship
class order extends eloquent { public function items() { return $this->belongstomany('product','order_items','order_id','product_id'); //assuming 'order_items' table has order_id , product_id foreign keys } }
you can work pivot table (order_items
table in case).
Comments
Post a Comment