更新时间:2023-10-02 11:56:34
查看 http://laravel.com/docs/5.1/eloquent-relationships ,他们使用以下示例:
//检索包含至少一个含有foo%
$ posts = Post :: whereHas('comments', function($ query){
$ query-> where('content','like','foo%');
}) - > get();
基于上述,您应该可以将约束放入您的评论中,其中Has的功能: / p>
$ venues = Venue :: whereHas('location',function($ query)use($ city){
$ query-> whereCityId($ city-> id);
})
- > whereHas('cuisines',function($ query)use($ cuisine){
$查询 - > whereName($ cuisine);
})
- > whereHas('reviews',function($ query)use($ minCount)
{
$ query - > where('score','>',3);
})
- > take(3) - > get();
您还可以通过在 - >之前或之后添加 - > count()来获取计数 - > get ),具体取决于用例。
I have these models, Venue, Review, User.
a User can score several venues.
A venue
has many reviews
A review
belongs to a venue
and user
on my Venue model I have a method which calculates score of a venue:
public function score()
{
$reviewCount = $this->reviews()->count();
$qualitySum = $this->reviews()->sum('quality') * 2;
$decorSum = $this->reviews()->sum('decor');
$venueAverage = ($qualitySum + $decorSum) / ($reviewCount * 30);
$minReview = 5;
//based on weighted average and Barnsley average
$average = ($reviewCount * Review::R()) / ($reviewCount + $minReview) + ($minReview * $venueAverage) / ($reviewCount + $minReview);
$average = round($average, 1);
return $average;
}
Here is the question: How can I retrieve those venues which score is >3
And how can I order results based on score
Looking at http://laravel.com/docs/5.1/eloquent-relationships they use the following example:
// Retrieve all posts with at least one comment containing words like foo%
$posts = Post::whereHas('comments', function ($query) {
$query->where('content', 'like', 'foo%');
})->get();
Based on above, you should be able to put the constraint into your "reviews" whereHas function:
$venues = Venue::whereHas('location', function ($query) use ($city) {
$query->whereCityId($city->id);
})
->whereHas('cuisines', function ($query) use ($cuisine) {
$query->whereName($cuisine);
})
->whereHas('reviews',function($query) use ($minCount)
{
$query->where('score', '>', 3);
})
->take(3)->get();
You can also get the count by adding ->count() either before or after ->get(), depending on your use case.