Laravel 5 ID 的 LEFT JOIN 问题

Laravel 5 LEFT JOIN issue with id's

我对 LEFT JOIN 有疑问。我不想使用 eloquent 关系,因为我想保持我的模型文件夹干净。我有一个约会应用程序,我在其中使用 "labels" 和 "statuses"。我希望能够根据标签和状态过滤我的视图。 LEFT JOIN 的问题是,当我想单击我的编辑 link 时,它使用我的 "appointments_statuses" table 中的 "id" 字段,而不是 [=26] =] table。下面是相关代码:

我的控制器:

$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

我的数据库tables:

CREATE TABLE IF NOT EXISTS `appointments` (
`id` int(11) NOT NULL,
`appointment` varchar(255) NOT NULL,
`location` varchar(255) NOT NULL,
`description` text NOT NULL,
`start` datetime NOT NULL,
`end` datetime NOT NULL,
`label_id` int(11) NOT NULL,
`status_id` int(11) NOT NULL,
`contact` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
)

CREATE TABLE IF NOT EXISTS `appointments_labels` (
`id` int(11) NOT NULL,
`label` varchar(255) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
)

CREATE TABLE IF NOT EXISTS `appointments_statuses` (
`id` int(11) NOT NULL,
`status` varchar(255) NOT NULL,
`flag` varchar(255) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
)

那是因为您的查询收集了 3 个表的所有字段,所以具有相同名称的列将被覆盖。 只需在您想要的字段上使用 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();

注意: 我猜你想从主表和连接表中获取哪些字段,但你明白了:)
NB2: 您还可以将 array 个值传递给 select() 方法:

->select(['appointments.id', 'appointments.name', ....])