鍍金池/ 問(wèn)答/PHP/ laravel 在文章列表中附帶上前10條評(píng)論?

laravel 在文章列表中附帶上前10條評(píng)論?

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

剛試了一下,在單數(shù)據(jù)的情況下是可以,在列表里面貌似是不行的,這個(gè) with 函數(shù)的加載只是優(yōu)化了一下第二步的 SQL 語(yǔ)句。就算知道了你第一句 SQL 獲取的 ID,如果要每條數(shù)據(jù)都取前十的關(guān)聯(lián)數(shù)據(jù),我認(rèn)為一條簡(jiǎn)單的 SQL 語(yǔ)句完成不了,因?yàn)椴还苣阆拗贫鄺l,都無(wú)法保證平均分配到每一條主數(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 中要顯示評(píng)論數(shù)據(jù)的地方 post->comments()->limit(10)

問(wèn)題:如果取了 20 條 Post 數(shù)據(jù),就會(huì)有 20 條取 comments 的 sql 語(yǔ)句,會(huì)造成執(zhí)行的 sql 語(yǔ)句過(guò)多。

不是非??扇?/blockquote>

方法2:

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

這里的 take 是 Laravel Collection 的方法。

兩種方法都可以去構(gòu)造其他查詢條件,過(guò)濾自己想要的數(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);
});
親測(cè)有效,會(huì)產(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');

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

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

2017年4月2日 06:23