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

User1980's avatar

Can Eloquent query AND USE the value of a previous relation within the same query?

Hi all,

No idea if my title makes any sense.

But I would like to know if this is possible with eloquent please:

ModelA::select(
                'id',
            )
                ->with('ModelB:id,name')
                ->with('ModelC:id,name')
                ->with(['ModelD' => static function ($query){
                    $query->where('ModelD.id','=', 'ModelB.id');
                    $query->where('ModelD.id2','=', 'ModelC.id');
                }])
->get();

In short, is there a way to use the value(id) of ModelB and ModelC(id) to query ModelD(2 id columns) in a relation? As I would like ModelD to return a column(image_url) when the IDs of both ModelB and ModelC are found in a ModelD row.

I am struggling to explain this in clear English sorry.....

0 likes
5 replies
User1980's avatar

@Sinnbeck Thank you for the reply. So would something like this makes sense?

ModelA::select(
                'id',
            )
                ->with('ModelB:id,name')
                ->with('ModelC:id,name')
                ->join('ModelD as modelcategory', 'ModelB.id', '=', 'ModelD.id')
                ->join('ModelD as modelsubcategory', 'ModelC.id', '=', 'ModelD.id2')
->get();

As I am having 2 joins on the same table.

User1980's avatar

It looks like I cannot join a predefined model to a table. I think I will have to put all the table names instead.

Sinnbeck's avatar

@User1980 Yeah joins are just raw sql. You join the results of two tables into one (and filter the result in the process)

1 like

Please or to participate in this conversation.