鍍金池/ 問答/PHP/ laravel 在文章列表中附帶上前10條評論?

laravel 在文章列表中附帶上前10條評論?

  1. with的話無法limit數(shù)量的
  2. take也一樣,查到的都是空
  3. 你們是怎么解決的啊?
  4. 也可以是只查詢各個文章的前10條評論?
回答
編輯回答
念初

剛試了一下,在單數(shù)據(jù)的情況下是可以,在列表里面貌似是不行的,這個 with 函數(shù)的加載只是優(yōu)化了一下第二步的 SQL 語句。就算知道了你第一句 SQL 獲取的 ID,如果要每條數(shù)據(jù)都取前十的關(guān)聯(lián)數(shù)據(jù),我認(rèn)為一條簡單的 SQL 語句完成不了,因為不管你限制多條,都無法保證平均分配到每一條主數(shù)據(jù)上。

2018年5月9日 09:49
編輯回答
硬扛
Post::find($id)->with(['comments'=>function($query){
     $query->orderBy('created_at','desc')->limit(10);
}])

------------ 分割線 ----------

如果 with 里的 limit 和 take 不行的話,那么就比較麻煩了,還有其他一些折中的方法。

方法1:

在 blade 中要顯示評論數(shù)據(jù)的地方 post->comments()->limit(10)

問題:如果取了 20 條 Post 數(shù)據(jù),就會有 20 條取 comments 的 sql 語句,會造成執(zhí)行的 sql 語句過多。

不是非??扇?/blockquote>

方法2:

直接通過 with 把 Post 的所有 comments 數(shù)據(jù)都取出來,在 blade 中 post->comments->take(10)

這里的 take 是 Laravel Collection 的方法。

兩種方法都可以去構(gòu)造其他查詢條件,過濾自己想要的數(shù)據(jù)。

方法3:

$posts = Post::paginate(15);

$postIds = $posts->pluck('id')->all();

$query = Comment::whereIn('post_id',$postIds)->select(DB::raw('*,@post := NULL ,@rank := 0'))->orderBy('post_id');

$query = DB::table( DB::raw("({$query->toSql()}) as b") )
            ->mergeBindings($sub->getQuery())
            ->select(DB::raw('b.*,IF (
            @post = b.post_id ,@rank :=@rank + 1 ,@rank := 1
        ) AS rank,
        @post := b.post_id'));

$commentIds = DB::table( DB::raw("({$query->toSql()}) as c") )
            ->mergeBindings($sub2)
        ->where('rank','<',11)->select('c.id')->pluck('id')->toArray();

$comments = Comment::whereIn('id',$commentIds)->get();

$posts = $posts->each(function ($item, $key) use ($comments) {
    $item->comments = $comments->where('post_id',$item->id);
});
親測有效,會產(chǎn)生三條sql
select * from `posts` limit 15 offset 0;

select `c`.`id` from (select b.*,IF (
@post = b.post_id ,@rank :=@rank + 1 ,@rank := 1
) AS rank,
@post := b.post_id from (select *,@post := NULL ,@rank := 0 from `comments` where `post_id` in ('2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16') order by `id` asc) as b) as c where `rank` < '11';

select * from `comments` where `id` in ('180', '589', '590', '3736');

其實該問題的難點是在于:在文章列表時候,要把文章的相關(guān)評論取N條,之前 withtake 不行,是因為 mysql 的語法不像 SQL ServerOrder 那樣支持 over partition by 分組。

所以方法3實現(xiàn)的是類似 over partition by 這樣的分組功能。comments 表根據(jù)post_id進(jìn)行分組,然后計數(shù)獲得 rank,然后取 rank < 11 的數(shù)據(jù),也就是前 10 條數(shù)據(jù)。

2017年4月2日 06:23