[英]Converting mysql query to Laravel query builder
我第一次使用 Laravel。 我有(例如,為了使關系易於理解) books 、 authors 、 author_book和descriptions表。 而且我需要將描述表作為單獨的表,不要問我為什么。
所以,我寫了一些 mysql 查詢來向你展示我的意圖。 它有一個子查詢,首先將所有作者作為字符串獲取。
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
此查詢檢索所有具有描述的書籍的列表,並按作者和標題對其進行排序。 像這兒:
- Alex Banks,Eve Porcello - 學習 React:使用 React 和 Redux 進行功能性 Web 開發
- Charlotte Lucas - Dein perfektes Jahr: Roman
- 夏洛特盧卡斯 - 你完美的一年:小說 Kindle 版 Marc
- Garreau, Will Faurot - Redux 在行動
我的問題是如何使用 Laravel 查詢生成器做同樣的事情?
你可以這樣
$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();
您在 laravel model class 中使用了hasOne
和hasMany
關系。
首先,您需要學習如何使用主鍵到外鍵的 laravel 中的連接 model。
如需更多信息,您需要參考此 URL 以加入 laravel 中的查詢。
請查看下面的 URL 以獲取連接查詢
Alex Guerrero的評論真的很有幫助。 我的解決方案就是基於它。 來自Saly 3301的提示使用在線轉換器https://pontaku-tools.com/english/可能很有用,但該工具不適用於復雜的查詢。
我還找到了一種方法來檢查 sql 字符串查詢生成器生成的內容。 可以在查詢構建器實例上調用 ->toSql() 方法。 您應該在調用 ->get() 或 ->paginate() 方法之前執行此操作。
$sql = DB::table('users')->toSql();
var_dump($sql);
我對 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.