Php Laravel 5左连接问题,id为

Php Laravel 5左连接问题,id为,php,laravel,join,left-join,Php,Laravel,Join,Left Join,我对左连接有问题。我不想使用雄辩的关系,因为我想保持我的模型文件夹干净。我有一个约会应用程序,我在其中使用标签和状态。我希望能够根据标签和状态筛选视图。左连接的问题是,当我想要单击我的编辑链接时,它使用my Appoints\u Status表中的id字段,而不是Appoints表中的id字段。以下是相关代码: 我的控制器: $appointments = $query->orderBy('appointment', 'asc') ->leftJoin('appointments_l

我对左连接有问题。我不想使用雄辩的关系,因为我想保持我的模型文件夹干净。我有一个约会应用程序,我在其中使用标签和状态。我希望能够根据标签和状态筛选视图。左连接的问题是,当我想要单击我的编辑链接时,它使用my Appoints\u Status表中的id字段,而不是Appoints表中的id字段。以下是相关代码:

我的控制器:

$appointments = $query->orderBy('appointment', 'asc')
->leftJoin('appointments_labels','appointments_labels.id','=','appointments.label_id')
->leftJoin('appointments_statuses','appointments_statuses.id','=','appointments.status_id')
->get();
我的看法是:

@foreach($appointments as $appointment)
    <a href="#">{{ $appointment->id }}</a> // Problem here, it uses the "status_id" field from the "appointments" table instead of the "id" field
@endforeach

这是因为您的查询收集了3个表的所有字段,因此同名的列会被覆盖。 只需选择您想要的字段,这是一种很好的做法:

$appointments = $query->orderBy('appointment', 'asc')
->leftJoin('appointments_labels','appointments_labels.id','=','appointments.label_id')
->leftJoin('appointments_statuses','appointments_statuses.id','=','appointments.status_id')
->select('appointments.id', 'appointments.name', '........', 'appointments_statuses.name', 'appointments_labels.name')
->get();
注意:我猜测您希望从主表和联接表中获得的字段,但您得到了这样的想法: NB2:您还可以将值数组传递给select方法:


太棒了,是的,很好的实践,这就是我构建这个应用程序的全部原因。谢谢,我相信我现在会让它发挥作用,所以我接受了答案:
$appointments = $query->orderBy('appointment', 'asc')
->leftJoin('appointments_labels','appointments_labels.id','=','appointments.label_id')
->leftJoin('appointments_statuses','appointments_statuses.id','=','appointments.status_id')
->select('appointments.id', 'appointments.name', '........', 'appointments_statuses.name', 'appointments_labels.name')
->get();
->select(['appointments.id', 'appointments.name', ....])