我如何在 db::select 中使用 paginate() 函数

how can i use paginate() function with db::select

首先,我对如何在简单查询中使用分页功能很感兴趣。 例如,我有这个查询:

$query = "SELECT 
 dw.id,
 w.word,
 d.definition,
 dw.user_id,
 IF(IFNULL(dw.definition_id, 0) = 0,
    (SELECT COUNT(phrase_id) 
     FROM phrase_word wp1 WHERE wp1.user_id = dw.user_id AND wp1.word_id = dw.word_id),
    (SELECT COUNT(phrase_id)
     FROM phrase_word wp2 WHERE wp2.user_id = dw.user_id AND wp2.word_id = dw.word_id AND wp2.definition_id = dw.definition_id)
   ) phrases_count
 FROM definition_word AS dw
 INNER JOIN words AS w ON w.id  = dw.word_id 
 LEFT JOIN definitions AS d ON d.id = dw.definition_id
 WHERE dw.user_id = 2";

我不能这样使用分页方法。 $unknown_words = DB::select($query)->paginate(5);

或者如果可能如何转换

"IF(IFNULL(dw.definition_id, 0) = 0,
    (SELECT COUNT(phrase_id) 
     FROM phrase_word wp1 WHERE wp1.user_id = dw.user_id AND wp1.word_id = dw.word_id),
    (SELECT COUNT(phrase_id)
     FROM phrase_word wp2 WHERE wp2.user_id = dw.user_id AND wp2.word_id = dw.word_id AND wp2.definition_id = dw.definition_id)
   ) phrases_count";

将这部分查询放入查询构建器中。

我认为你有更好的选择,你可以使用 laravel 加入 select 和 table 方法,你可以实现你想要的输出,如下所示。

 $unknown_words = DB::table('definition_word as dw')
 ->join('words as w', 'w.id', '=', 'dw.word_id')
 ->leftJoin('definitions as d', 'd.id', '=', 'dw.definition_id')
 ->select(
    'dw.id',
    'w.word',
    'd.definition',
    'dw.user_id',
        DB::raw('IF(IFNULL(dw.definition_id, 0) = 0,
            (SELECT COUNT(phrase_id) 
            FROM phrase_word wp1 WHERE wp1.user_id = dw.user_id AND wp1.word_id = dw.word_id),
            (SELECT COUNT(phrase_id)
            FROM phrase_word wp2 WHERE wp2.user_id = dw.user_id AND wp2.word_id = dw.word_id AND wp2.definition_id = dw.definition_id)
        ) as phrases_count')
    )->where('dw.user_id', 2)->paginate(15)