Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

KodaC's avatar
Level 1

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.

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

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

1 like
KodaC's avatar
Level 1

I have never used "with()". This is amazing. Thank you very much.

Please or to participate in this conversation.