Save Query on Relationship
Sorry I have a second question today
How can I save querys in a relationship
Simple example:
I have two tables: transactions and images with the shortened columns
transactions
| id | image_id | data1 | ....
| --- | ---------- | ------- | -
| 1 | 2 | ...
| 2 | 2 | ...
| 3 | 2 | ...
| 4 | 1 | ...
In my Blade I use $transaction->image->image_url
The problem is that I now have 4 queries, but 3 of them are the same because they contain the same image.
Define an image relationship on Transaction
public function image()
{
return $this->belongsTo(Image::class);
}
Then eager load that relationship
$transactions = Transaction::with('image')->get();
Now there’s a maximum of two queries
I have never used "with()". This is amazing. Thank you very much.
Please or to participate in this conversation.