如何为此 SQL 查询使用此 laravel 查询生成器

How to use this laravel query builder for this SQL Query

我有这个查询:

SELECT `topic_posts`.*, `users`.`id` AS `adminID`, `users`.`name` as `adminName` FROM `topic_posts` INNER JOIN `topics` ON `topics`.`id` = `topic_posts`.`topic` INNER JOIN `users` ON `users`.`id` = `topic_posts`.`player` WHERE `users`.`playerAdminLevel` > 0 AND `topics`.`type` = 0 GROUP BY (`topic_posts`.`id`)

我想在 Laravel 中使用,例如:

$result = DB::table('topic_posts`)->join..etc 而且,使用 ->paginate(20)

我该怎么做?

实现您所需要的可能性很小。

select,整个 SQL 查询:

DB::select('select topic_posts,* .....');

在此处查看更多信息: https://laravel.com/docs/4.2/database#running-queries

或者您也可以采用开始构建查询的方式,例如:

DB::table('topic_posts')
        ->join('topics', 'topics.id', '=', 'topic_posts.topic')
        ->join('users', 'users.id', '=', 'topic_posts.player')
        ->select('`topic_posts`.*', 'users.id') ... 

可在此处找到更多信息: https://laravel.com/docs/9.x/queries#inner-join-clause

SELECT `topic_posts`.*, `users`.`id` AS `adminID`, `users`.`name` as `adminName` FROM `topic_posts` INNER JOIN `topics` ON `topics`.`id` = `topic_posts`.`topic` INNER JOIN `users` ON `users`.`id` = `topic_posts`.`player` WHERE `users`.`playerAdminLevel` > 0 AND `topics`.`type` = 0 GROUP BY (`topic_posts`.`id`)

会是这样的(我必须稍微更改一下查询,因为您似乎没有正确使用 group by):

DB::table('topic_posts')
->join('topics', 'topic.id', '=', 'topic_posts.topic')
->join('users', 'users.id', '=', 'topic_posts.player')
->select('topic_posts.id', 'users.id as adminID', DB::raw('count(topic_posts.id) as totalTopicPosts'))
->where('users.playerAdminLevel', '>', 0)
->where('topics.topics', 0)
->groupBy('topic_posts.id', 'users.id')
->paginate(20)

但是如果你想使用分组依据,首先要确保你有一些聚合,比如计数之类的。在此处查看文档:https://www.tutorialspoint.com/sql/sql-group-by.htm