Laravel子联接选择查询

时间:2018-11-07 17:43:11

标签: php laravel-5 eloquent

我正在尝试找出如何在Laravel中复制以下查询。我正在尝试从table2 / t2获取最新状态,并将其与我们的主要记录table1 / t1

合并
select id, created_at, t2.status from table1 t1

left join table2 t2 ON 52.id = (
    SELECT MAX(id) from table2
    where table2.submission_id = submission_id
) AND t1.id = t2.submission_id

上面的查询效果很好,但是我无法弄清楚如何在“本地” Laravel中复制它-

$query = Table1::query();
$query->join('table2 as t2', function (JoinClause $join) {
    $join->selectRaw('MAX(id)')
        ->where('t2.submission_id', '=', 'submission_id');
}, '=', 't2.id');

我也尝试了joinSub-

$query->joinSub(function (Builder $query) {
                $query
                    ->selectRaw('MAX(id)')
                    ->from('table2 as t2')
                    ->where('t2.submission_id', '=', 'bespoke_submission_id');
            }, 't2', 't1.id', '=', 't2.id', 'left');

但是我似乎无法获得理想的结果!有什么想法吗?

3 个答案:

答案 0 :(得分:2)

您必须使用whereColumn()而不是where()

->whereColumn('t2.submission_id', '=', 'bespoke_submission_id')

答案 1 :(得分:1)

此代码可能有效,

DB::table('table1 t1')
->select(['id', 'created_at', 't2.status'])
->leftJoin('table2 t2', function ($join) {
    $subQuery = DB::table('table2')
                    ->selectRaw('MAX(id)')
                    ->whereRaw('table2.submission_id = submission_id');
    $join->on('t2.id', DB::raw('(' . $subQuery->toSql() . ')'))->whereRaw('t1.id = t2.submission_id');
});

或者这个

DB::table('table1 t1')
->select(['id', 'created_at', 't2.status'])
->leftJoin('table2 t2', function ($join) {
    $subQuery = DB::raw('(select MAX(id) from table2 where table2.submission_id = submission_id)');
    $join->on('t2.id', $subQuery)->whereRaw('t1.id = t2.submission_id');
});

注意:在执行查询字符串之前,可以使用->toSql()方法打印出查询字符串,以确保您确实获得了所需的查询。

答案 2 :(得分:1)

谢谢。我的最终解决方案如下-

// write begin making our query
$query = Model::query();

// filter by status
$args = ['status' => 'approved'];

// create our sub query
$subQuery = DB::raw(
    '(SELECT MAX(id) from table2 ' .
    'where t2.submission_id = submission_id)'
);

// join to retrieve our revisions table
$query->leftJoin('table2 as t2', 't2.id', '=', $subQuery);
$query->whereColumn('table1.id', '=', 't2.submission_id');
$query->where('t2.status', '=', $args['status']);

$results = $table->get();

然后创建所需的结果,因此感谢@Kyaw Kyaw Soe提出的实现DB::raw()的指针,以及@Jonas Staudenmeir提出的$query->whereColumn()的技巧