我对LEFT JOIN有问题。我不想使用雄辩的关系,因为我想保持我的模型文件夹干净。我有一个约会应用程序,在其中使用“标签”和“状态”。我希望能够根据标签和状态过滤视图。LEFT JOIN的问题在于,当我想单击编辑链接时,它使用的是我的“ appointments_statuses”表中的“ id”字段,而不是“ appointments”表。下面是相关代码:
我的控制器:
$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
我的数据库表:
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()
在所需字段上使用a (无论如何都是一种好习惯):
$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();
注意:我正在猜测要从主表和联接表中获取的字段,但是您知道了:)注意2
:您还可以将array
值的一个传递给select()
方法:
->select(['appointments.id', 'appointments.name', ....])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句