Laravel 5.3查询 - 左连接一些表

时间:2017-01-20 14:27:04

标签: mysql laravel-5 laravel-eloquent

我正试图从“视图”表中获取每个candidate_id的最新记录。

这就是我想要实现的目标: enter image description here

我在laravel上使用Eloquent并且已经尝试过这种方法(有和没有说服力):

$candidates = DB::table('interviews')->select('interviews.*', 'i2.*')
->leftJoin('interviews as i2',
    function ($join) {
        $join->on('interviews.candidate_id', '=', 'i2.candidate_id');
        $join->on('interviews.created_at', '<', 'i2.created_at');
    }
)
->whereNull('i2.candidate_id')
->get();

并且雄辩地说我试过这个:

    $candidates = Interview::leftJoin('interviews as i2',
    function ($join) {
        $join->on('interviews.candidate_id', '=', 'i2.candidate_id');
        $join->on('interviews.created_at', '<', 'i2.created_at');
    }
)->whereNull('i2.candidate_id')
->get();

如果我将get()更改为toSql()我在上面的图片上显示的查询完全相同,但在laravel上运行我总是得到这些结果(这使用第一种方法,带有查询建设者): enter image description here

任何人都知道为什么我会得到这个结果?很难理解laravel正在做我在HeidiSql中做的相同查询但是我得到了不同的结果:(

任何提示?

提前致谢!

1 个答案:

答案 0 :(得分:1)

因为您使用->select('interviews.*', 'i2.*')->whereNull('i2.candidate_id')结合使用我假设第二个选择参数覆盖了与nulls的访谈表中的所有字段,请尝试将订单撤消到->select('i2.*','interviews.*')或者根本不使用i2.*

这是因为输出会忽略别名,并且只在返回的集合中使用fieldname作为元素键。

希望它有效。

完美案例场景,您可以从每个连接表中选择所需的确切列,例如:它可能是这样的:table1.id,table1.column1,table1.column2,table2.column2 as smth_so_it_doesnt_override

相关问题