Laravel 如何获取相关表的摘要?
在laravel 7应用程序中,我有两个与UMThread相关的表:Laravel 如何获取相关表的摘要?,laravel,eloquent,Laravel,Eloquent,在laravel 7应用程序中,我有两个与UMThread相关的表: Schema::create('forum_threads', function (Blueprint $table) { $table->increments('id')->unsigned(); ... $table->integer('forum_id')->unsigned(); $table->foreign('forum_id')->referen
Schema::create('forum_threads', function (Blueprint $table) {
$table->increments('id')->unsigned();
...
$table->integer('forum_id')->unsigned();
$table->foreign('forum_id')->references('id')->on('forums')->onUpdate('RESTRICT')->onDelete('CASCADE');
});
对于UMPOST:
Schema::create('forum_posts', function (Blueprint $table) {
$table->bigIncrements('id')->unsigned();
...
$table->integer('forum_thread_id')->unsigned();
$table->foreign('forum_thread_id')->references('id')->on('forum_threads')->onUpdate('RESTRICT')->onDelete('CASCADE');
...
$table->integer('viewed')->unsigned()->default(0);
});
最后一个字段已查看,我需要计算相关论坛文章行的已查看字段的总和。
在模型app/ForumThread.php中,我添加了forumPostsViewedSum方法:
public function forumPosts()
{
return $this->hasMany('App\ForumPost');
}
public function forumPostsViewedSum()
{
return $this->hasMany('App\ForumPost')
->selectRaw('SUM(viewed) as forum_posts_viewed_sum')
->groupBy('forum_thread_id');
// ->groupBy('forum_id');
}
在控制器中:
$forumThreads = ForumThread
::with('latestForumPost.creator')
->withCount('forumPosts')
->with('creator')
->getByForumId($forum_id)
->orderBy($order_by, $order_direction)
->offset($limit_start)
->take($forum_threads_per_page)
->with('forumPostsViewedSum')
->get();
\Log::info(varDump($forumThreads, ' get_forum_threads -3 $forumThreads::'));
通过查看跟踪sql,我知道我需要什么
SELECT *
FROM `vfrm_forum_posts`
WHERE `vfrm_forum_posts`.`forum_thread_id` in (2, 3)
ORDER BY `created_at` desc
...
SELECT SUM(viewed) AS forum_posts_viewed_sum
FROM `vfrm_forum_posts`
WHERE `vfrm_forum_posts`.`forum_thread_id` in (2, 3)
GROUP BY `forum_thread_id`
上一个请求返回了我期望的数据,但在返回的数据和跟踪的数据(Log::info)中,我得到了论坛帖子的空数组
为什么论坛帖子的数据无效?我怎么做
谢谢