Cakephp 3.5 InnerJoin

时间:2018-01-09 14:17:19

标签: mysql cakephp inner-join cakephp-3.x

我有以下情况。 我有一张桌子" drivers_events"在这里存储了为活动预订的司机。 现在我想做以下

SELECT
    Driver.id,
    Driver.name 
FROM
    drivers AS Driver 
    INNER JOIN
        drivers_events AS Listing 
        ON Driver.id = Listing.driver_id 
WHERE
    Listing.event_id = 83 
ORDER BY
    Driver.name ASC;

如果我在phpmyadmin中将其作为SQL查询运行,它可以正常工作,我从表中获得了正确的ID和名称" drivers"。

当我在我的控制器中执行此操作时

$drivers = $this->Jobs->query("
    SELECT
        Driver.id,
        Driver.name 
    FROM
        drivers AS Driver 
        INNER JOIN
            drivers_events AS Event 
            ON Driver.id = Event.driver_id 
    WHERE
        Event.event_id = $activeevent 
    ORDER BY
        Driver.name ASC
");

然后我获得了过去创建的完整作业数组。

我做错了什么?

如果有人可以帮助我,那就太棒了。

提前致谢

3 个答案:

答案 0 :(得分:0)

事件关键字是为SQL保留的。 请不要将它用于表别名。 或者使用这种方法。

drivers_events AS `Event`

希望有用。

$result = $this->Jobs->find()
        ->enableAutoFields(true)
        ->enableHydration(false)
        ->select([
            'id' => 'Driver.id',
            'Title' => "Driver.name"
        ])
         ->join([
            'Events' => [
                'table' => 'drivers_events',
                'type' => 'INNER',
                'conditions' => [
                    'Jobs.event_id = Events.id',

                ],
            ]
        ])
        ->join([
            'Driver' => [
                'table' => 'drivers',
                'type' => 'INNER',
                'conditions' => [
                    'Events.driver_id = Driver.id',
                ],
            ]
        ])
        ->where([
            'Events.id' => $activeevent
        ])
        ->group('Driver.id')
        ->toArray();

参考:Cakephp 3 Adding Joins

答案 1 :(得分:0)

我尝试了很多。我得出的结论是,我可以读出分配给某个活动的司机。

控制器中的

看起来像这样

$(document).ready(function() {
    $('#some-menu').load('some-local-path/menu.html');
});

在模型中

 $drivers = $this->Jobs->drivers_events->find('list',
      [
      'conditions' =>
      [
           'drivers_events.event_id' => $this->request->session()->read('Event.active')
      ],
      'keyField' => 'driver_id',
      'valueField' => 'driver_id'
      ]
 );

所以现在我在活动中获得了正确的驾驶员工作。 但是如何从" Drivers"中获取驱动程序的名称?表而不是ID?

寻求帮助

答案 2 :(得分:0)

Select Drivers.id, drivers.accountname

FROM TABLE__

Join table__
Join table__

And (Brand) Totaljobs.com

Having Count <4

group By Driver.id, Drivers.Accountname

Order by (Drivers.accountname)