let’s say I’ve this kind of structure.
| lines | | products | | orders | |------------| |----------| |--------| | id | | id | | id | | product_id | |----------| |--------| | order_id | |------------|
Is there a way in Laravel Eloquent to load related products given an order? I’ve tried with hasManyThrough(Product::class, Line::class)
with no luck, because on products table there’s no reference to the order. Is there a method that can resolve this relationship or should I write a raw query?
Advertisement
Answer
You can create a many-to-many relationship in Order model:
class Order extends Model { public function products() { return $this->belongsToMany('AppProduct','lines', 'order_id', 'product_id'); } }
Then you can get products related to an order:
$order_id = 12; $order = Order::find($order_id); $order_products = $order->products;