本文介紹了Laravel:讓 Eloquent 創(chuàng)建嵌套 SELECT 的正確方法的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我試圖雄辯地生成的查詢是
The query I am trying to get eloquent to generate is
SELECT *, (SELECT COUNT(comment_id) FROM comment AS c WHERE c.approved=true AND c.blog_fk=b.blog_id) AS comment_count FROM blog AS b
這是結(jié)果
blog_id | title | author | blog | image | tags | created | updated | comment_count
--------|-------------------|--------------|----------------|------------------|---------|---------------------|---------------------|--------------
21 | A day.. | dsyph3r | Lorem ipsum... | beach.jpg | symf... | 2014-12-22 19:14:34 | 2014-12-22 19:14:34 | 2
22 | The pool .. | Zero Cool | Vestibulum ... | pool_leak.jpg | pool,.. | 2011-07-23 06:12:33 | 2011-07-23 06:12:33 | 10
23 | Misdirection... | Gabriel | Lorem ipsum... | misdirection.jpg | misd... | 2011-07-16 16:14:06 | 2011-07-16 16:14:06 | 2
24 | The grid ... | Kevin Flynn | Lorem commo... | the_grid.jpg | grid... | 2011-06-02 18:54:12 | 2011-06-02 18:54:12 | 0
25 | You're either ... | Gary Winston | Lorem ipsum... | one_or_zero.jpg | bina... | 2011-04-25 15:34:18 | 2011-04-25 15:34:18 | 2
我目前使用 DB::select(DB::raw()) 運行它,這可能不是正確的方法.
I currently have this running by using DB::select( DB::raw()) which probably isn't the correct way to do this.
問題是什么才是能夠產(chǎn)生這些結(jié)果的查詢的正確方法?
The question is what is the proper way to get eloquent to produce the query that generates those results?
推薦答案
改用這個:http://softonsofa.com/tweaking-eloquent-relations-how-to-get-hasmany-relation-count-高效
對于嵌套的 select
/join
語句,您需要:
$sub = Comment::selectRaw('count(comment_id) as count')
->where('approved', '?')
->where('comment.blog_fk', '?')
->toSql();
Blog::selectRaw(DB::raw("blog.*, ({$sub}) as comment_count"))
->setBindings([true, DB::raw('blog.blog_id')], 'select')
->get();
或者干脆把所有東西都放在selectRaw
中.
Or simply put everything in selectRaw
.
這篇關(guān)于Laravel:讓 Eloquent 創(chuàng)建嵌套 SELECT 的正確方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!