我试图通过Post获得的票数来订购帖子表.
投票存储在另一个表中
(Votes: post_id, user_id, vote_type)
后期型号:
class Post extends Model
{
public function user()
{
return $this->hasOne(User::class);
}
public function votes()
{
return DB::table('votes')->where('post_id','=',$this->id)->sum('vote_type');
}
}
投票函数返回一个帖子收到的投票数(投票存储在一个单独的表中)
现在我试图通过他们获得的票数来订购所有帖子.
Post::get()->sortBy('votes');
这将返回以下错误:
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
我会感谢任何帮助解决这个问题!
解决方法:
试试看
Post::get()->sortBy(function($query){
return $query->votes();
});
替代
您可以使用withCount(),因为它会在结果模型上放置{relation} _count列.
Post::withCount(['votes'])
->orderBy('votes_count')
->get()
对于分页
有关分页的更多详细信息,请参阅docs
Post::withCount(['votes'])
->orderBy('votes_count')
->paginate();
标签:php,mysql,laravel
来源: https://codeday.me/bug/20190627/1305983.html