我有一个Post
,对于每个帖子,Likes
表格中有多个likes
。我在total_likes
表中创建了一个Posts
字段,我想在一个语句中用likes
表中的喜欢总数来更新它。我目前有这个:
DB::table('posts as p')
->update(['total_likes' => function($query) {
$query->select(DB::raw('COUNT(*)'))
->from('likes as l')
->where(DB::raw('p.id = l.post_id'))
->groupBy('l.post_id');
}]);
但是我收到了一个错误:
类Closure的对象无法转换为字符串
我基本上是想跑:
UPDATE posts SET total_likes = (SELECT COUNT(id) FROM likes WHERE likes.post_id = posts.id GROUP BY id);