Laravel Query Builder Foreach Loop 如何引用存在于两个连接表中的字段

Laravel Query Builder Foreach Loop how do I reference a field that exists in both join tables

foreach 循环中的 id 字段存在于我加入的两个 table 中,我只需要将它引用到一个 table(即 program_types.id)在 foreach 循环中:

$program_details = DB::table('program_allocation')
                ->where('twilio_wa_from_no', '=', $tophonenumber)
                ->where('twilio_sid' , $account_sid)
                ->join('program_types', 'program_allocation.program_type', '=', 'program_types.id')
                ->get();

foreach ($program_details as $program) {  
        $program_allocation_id = $program->id;
}

您可以使用 select('program_allocation.*', 'program_types.id AS program_type_id') 来指定要使用的查询中包含哪些表的哪些列。

$program_details = DB::table('program_allocation')
    ->where('twilio_wa_from_no', '=', $tophonenumber)
    ->where('twilio_sid', $account_sid)
    ->join('program_types', 'program_allocation.program_type', '=', 'program_types.id')
    ->select('program_allocation.*', 'program_types.id AS program_type_id')
    ->get();

你可以在官方Laravel文档上查看:https://laravel.com/docs/9.x/queries#inner-join-clause

Select 字段并给其中一个连接 table id 一个别名

$program_details = DB::table('program_allocation')
                ->join('program_types', 'program_allocation.program_type', '=', 'program_types.id')
                ->select('program_types.*', 'program_allocation.id as allocationID', )
                ->where('twilio_wa_from_no', '=', $tophonenumber)
                ->where('twilio_sid' , $account_sid)
                ->get();