尝试将查询转换为雄辩

时间:2019-04-22 17:25:47

标签: mysql laravel eloquent

我有以下SQL:

SELECT arv.* 
FROM   article_reference_versions arv 
       INNER JOIN (SELECT `order`, 
                          Max(`revision`) AS max_revision 
                   FROM   article_reference_versions 
                   WHERE  `file` = '12338-230180-1-CE.doc' 
                   GROUP  BY `file`, 
                             `order`) AS b 
               ON arv.order = b.order 
                  AND arv.revision = b.max_revision 
WHERE  arv.file = '12338-230180-1-CE.doc' 

我需要将其转换为Eloquent,以便可以正确访问对象形式的数据。我尝试这样做,

$s = Models\EloArticleReferenceVersion::select(
    'SELECT arv.*
    FROM article_reference_versions arv
        INNER JOIN (
            SELECT `order`, max(`revision`) as max_revision
            FROM article_reference_versions
            WHERE file = ? group by `file`, `order`) AS b
        ON 
            arv.order = b.order AND arv.revision = b.max_revision 
            WHERE arv.file = ?',
        [ 
            '12338-230180-1-CE.doc', 
            '12338-230180-1-CE.doc' 
        ])->get();
dd($s);

但是我遇到了很多问题,一个接一个。我认为将其转换为雄辩的查询会更容易,从而寻求一些帮助。

1 个答案:

答案 0 :(得分:0)

数据库查询以使用口才查询。

$query = EloArticleReferenceVersion::query()
    ->join(DB::raw('( SELECT `order`,Max(`revision`) AS max_revision FROM article_reference_versions WHERE  `file` = '12338-230180-1-CE.doc' GROUP  BY `file`, `order`) as sub_table'), function($join) {
    $join->on('sub_table.order', '=', 'article_reference_versions.order');
    $join->on('sub_table.max_revision ', '=', 'article_reference_versions.revision');
})
->where('article_reference_versions.file', '=', '12338-230180-1-CE.doc' )
->get();

未测试