将原始查询转换为Laravel查询构建器

时间:2016-11-15 12:46:18

标签: laravel

我有以下MySQL查询,它提取最后9位作者的列表来撰写帖子,并按照他们写的最后一篇文章的日期顺序列出。

它工作正常,但我想使用Laravel Query Builder重新编写它。以下是查询:

    $authors = DB::select("
        SELECT 
            `a`.`id`, 
            `a`.`name`, 
            `a`.`avatar`, 
            `a`.`slug` AS `author_slug`, 
            `p`.`subheading`, 
            `p`.`title`, 
            `p`.`slug` AS `post_slug`, 
            `p`.`summary`, 
            `p`.`published_at`
        FROM 
            `authors` AS `a`
        JOIN 
            `posts` AS `p`
             ON `p`.`id` =
              (
                 SELECT `p2`.`id`
                 FROM `posts` AS `p2`
                 WHERE `p2`.`author_id` = `a`.`id`
                 ORDER BY `p2`.`published_at` DESC
                 LIMIT 1
              )
        WHERE 
            `a`.`online` = 1
        ORDER BY 
            `published_at` DESC
        LIMIT 9
    ");

我了解使用查询构建器的基础知识,但Laravel文档中似乎没有任何内容允许我JOIN表格ONSELECT

任何人都可以建议我使用“Laravel查询”构建器编写此查询的方法,或者建议我可以重写此查询以便更轻松地使用查询构建器进行构建吗?

1 个答案:

答案 0 :(得分:1)

尝试这样做

    $data = DB::table('authors')
        ->select(
            'a.id',
            'a.name',
            'a.avatar',
            'a.slug AS author_slug',
            'p.subheading',
            'p.title',
            'p.slug AS post_slug',
            'p.summary',
            p.published_at')
        ->from('authors AS a')
        ->join('posts AS p', 'p.id', '=', DB::raw("
            (
                SELECT p2.id FROM posts AS p2 
                WHERE p2.author_id = b.id 
                ORDER BY p2.published_at 
                DESC LIMIT 1
            )"))
        ->where('a.online', 1)
        ->limit(9)
        ->orderBy('p.published_at', 'desc')
        ->get();