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

Hassaan's avatar

How can i send one query result (via variable) into an other query

What I want is to include the result of sub variable into another query.

 $sub = DB::table('chef_food_ethics')->
 select(DB::raw('count(id) as fCount'))
 ->where('chef_food_ethics.food_ethic_id',
 '=','food_ethic_managers.food_ethic_id')
 ->toSql();

Is it possible to include it like that?

 $r = DB::table('food_ethic_managers')where
 ('food_ethic_managers.manager_id','=',$id)
 ->leftJoin('staff','food_ethic_managers.food_ethic_id'
  ,'=','staff.id')
 ->leftJoin('regions','staff.region_id','=','regions.id')
 ->with($sub)
 ->get();
0 likes
4 replies
Hassaan's avatar

@Cinek I tried $r = DB::table('food_ethic_managers')where ('food_ethic_managers.manager_id','=',$id) ->leftJoin('staff','food_ethic_managers.food_ethic_id' ,'=','staff.id') ->leftJoin('regions','staff.region_id','=','regions.id') ->union($sub) ->get(); but it is giving me **Cardinality violation: 1222 The used SELECT statements have a different number of columns **

Cinek's avatar

chef_food_ethics and food_ethic_managers should have same quantity of columns. You can use select to specify which columns should be selected in both queries. Can you tell me what you want to do?

Hassaan's avatar

@Cinek want to get the count of chefs against that food ethic and add(concatenate) it to result

Please or to participate in this conversation.