This has been driving me mad, because this is a question asked over and over, but the answers all seem to miss the point and provide a different solution than was asked.
What I would like to do, is to create a custom relationship method so that I can get a bunch of related models from a model instance, given an arbitrary relationship between those models.
We are used to this kind of thing out of the box:
public function order
Then we can get the order model from an orderline like this:
$order = $orderline->order;
Simple. Magic stuff happens in
belongsTo() - that method generates a relationship object. The relationship object is quite hard to understand, and I have not got my head around it. So my use case is that I want to do this:
$orders = $product->orders;
A product can be on many orderlines (many-to-many, with pivot table). An orderline is for an order. I would like to do this in one simple query, so the query will include a
group by so I don't get orders multiple times (a product may be on several order lines in a single order).
So, how can I do this? What would the
order() method look like? Now, I could create a
getMeTheOrders() method that looks up the orderlines, gets the orders for each, throws away any duplicate orders, then returns the result. I don't want to do all those queries when this can be done in one query. Similarly, I want to avoid a sub-select query, as they can be very slow in MySQL since they don't get optimised well at all.
Any examples out there? Is this actually a lot more complex than I am hoping it is (considering that I cannot see this question really cracked yet, often asked wrt being able to find related records via a pivot table.