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

36864's avatar
Level 13

Populating multiple relations from the same query result

I have a couple of models that have similar relations to a third model. I'd like to reduce database queries by either caching the query result or reusing one result to populate relations.

This is how my models are set up:

public class A{
    public function relatedC(){
        return $this->belongsTo(C::class);
    }
}
public class B{
    public function relatedC(){
        return $this->belongsTo(C::class);
    }
}
public class C{
    public function relatedAs(){
        return $this->hasMany(A::class);
    }
    public function relatedBs(){
        return $this->hasMany(B::class);
    }

}

Ideally I'd like to do something like this with only one database query, using the results I got from the get all to populate the relations:

$all_c = C::all();
$all_a = A::with('relatedC')->get();
$all_b = B:with('relatedC')->get();

Is there any built-in functionality to do this or do I have to implement it myself?

0 likes
3 replies
Paschal's avatar

Use Eloquent Relationships. Read more about it in Laravel docs.

That is the solution you are looking for.

36864's avatar
Level 13

I can't find anything in the docs about populating multiple relationships with the same query or from existing data.

As you can clearly see from the code I posted, I am already using Eloquent Relationships as you suggested. The problem is, in the use case I posted on my last code block, Eloquent query C three times. Once to populate $all_c, once to populate $all_a->c and once to populate $all_b->c.

What I want is a way to tell eloquent that I already have a collection of all Cs that it can use to populate relations on other models.

36864's avatar
Level 13

I've had limited success manually setting the property on a model like this:

$all_c = C::all();
$all_a = A::get();
foreach($all_a as $a)
    $a->c = $all_c->where('id', $a->c_id);

This trades off server cycles for database connections and is far from an ideal solution.

Now that 5.5 is out, is there anything that might help with this kind of situation?

Please or to participate in this conversation.