简体   繁体   English

将 mysql 查询转换为 Laravel 查询生成器

[英]Converting mysql query to Laravel query builder

I am working with Laravel first time.我第一次使用 Laravel。 I have (just for example, to make relations easy to understand) books , authors , author_book and descriptions tables.我有(例如,为了使关系易于理解) booksauthorsauthor_bookdescriptions表。 And I need descriptions table as separate table, don't ask me why.而且我需要将描述表作为单独的表,不要问我为什么。

So, I wrote some mysql query to show you my intentions.所以,我写了一些 mysql 查询来向你展示我的意图。 It has a subquery to get all authors as a string first.它有一个子查询,首先将所有作者作为字符串获取。

    SELECT temp.book_id, temp.names, books.title FROM descriptions 
        LEFT JOIN books ON descriptions.book_id = books.id 
        LEFT JOIN (     
            SELECT author_book.book_id, GROUP_CONCAT(authors.name ORDER BY authors.name SEPARATOR ', ') as names FROM author_book 
                LEFT JOIN authors ON author_book.author_id = authors.id 
            GROUP BY author_book.book_id) temp ON temp.book_id = books.id 
    ORDER BY temp.names, books.title

This query retrieves the list of all books, which have description, and orders them by authors and titles.此查询检索所有具有描述的书籍的列表,并按作者和标题对其进行排序。 Like here:像这儿:

  • Alex Banks, Eve Porcello - Learning React: Functional Web Development with React and Redux Alex Banks,Eve Porcello - 学习 React:使用 React 和 Redux 进行功能性 Web 开发
  • Charlotte Lucas - Dein perfektes Jahr: Roman Charlotte Lucas - Dein perfektes Jahr: Roman
  • Charlotte Lucas - Your Perfect Year: A Novel Kindle Edition Marc夏洛特卢卡斯 - 你完美的一年:小说 Kindle 版 Marc
  • Garreau, Will Faurot - Redux in Action Garreau, Will Faurot - Redux 在行动

My question is how can I do the same thing using Laravel query builder?我的问题是如何使用 Laravel 查询生成器做同样的事情?

you can make it like this你可以这样

$subJoin = 
author_book::select('author_book.book_id',DB::raw('GROUP_CONCAT(authors.name ORDER BY 
authors.name SEPARATOR ', ') as names'))
->leftJoin('authors','author_book.author_id','=','authors.id')
->groupBy(author_book.book_id)
->get();

$query = descriptions::leftJoin('books','books.id','=','descriptions.book_id')
                  ->joinSub($subJoin,'temp',function ($join) {
                    $join->on('temp.book_id', '=', 'books.id');

                })->orderBy('temp.names', 'books.title')
                  ->get();

You have used hasOne and hasMany Relationship in the laravel model class.您在 laravel model class 中使用了hasOnehasMany关系。

First, you need to learn how to use the join model in laravel with the primary key to foreign key.首先,您需要学习如何使用主键到外键的 laravel 中的连接 model。

for more information, you need to refer this URL to join query in laravel.如需更多信息,您需要参考此 URL 以加入 laravel 中的查询。

Please check below URL for a join query请查看下面的 URL 以获取连接查询

https://laravel.com/docs/5.8/eloquent-relationships https://laravel.com/docs/5.8/eloquent-relationships

Comment from Alex Guerrero was really helpfull. Alex Guerrero的评论真的很有帮助。 My solution is based on it.我的解决方案就是基于它。 Tip from Saly 3301 to use online converter https://pontaku-tools.com/english/ could be usefull, but the tool doesn't work well with complicated queries.来自Saly 3301的提示使用在线转换器https://pontaku-tools.com/english/可能很有用,但该工具不适用于复杂的查询。

I also found a way to check what sql string query builder generates.我还找到了一种方法来检查 sql 字符串查询生成器生成的内容。 It is possible to call ->toSql() method on query builder instance.可以在查询构建器实例上调用 ->toSql() 方法。 You should do it before calling ->get() or ->paginate() methods.您应该在调用 ->get() 或 ->paginate() 方法之前执行此操作。

    $sql = DB::table('users')->toSql();
    var_dump($sql);

My final solution for Laravel 5.8:我对 Laravel 5.8 的最终解决方案:

    $joined_authors = DB::table('author_book')
        ->select('author_book.book_id', DB::raw('GROUP_CONCAT(authors.name ORDER BY authors.name SEPARATOR ", ") as names'))
        ->leftJoin('authors', 'author_book.author_id', '=', 'authors.id')
        ->groupBy('author_book.book_id');

    $books_with_description = DB::table('descriptions')
        ->leftJoin('books', 'descriptions.book_id', '=', 'books.id')
        ->leftJoinSub($joined_authors, 'joined_authors', function ($join) {
            $join->on('joined_authors.book_id', '=', 'books.id');
        })
        ->orderBy('joined_authors.names')
        ->orderBy('books.title')
        ->paginate(15);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM