larvel mysql count,php – 模型中的Laravel计数函数,然后sortBy count()

我试图通过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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值