我有store
表与product
表相关,有product.rating
(int)1到5
我想找到平均产品评级为3星或任何基于我的帖子数据的商店
我的代码
$store = new Store;
if ((int)$request->input('store-rating')>0) {
$store->whereHas('product',function($query) use($request) {
$rate = $request->input('product-rating');
$query->where(DB::raw('AVG(rating)'),$rate);
});
}
$store->with('product');
$thestore = $store->paginate(6);
return $thestore;
它始终返回所有数据,例如忽略我的POST store-rating
值
这是我的模特
<?php
namespace App;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as AuthUser;
use Illuminate\Support\Facades\Auth;
use App\ModelBuilder;
class Store extends AuthUser
{
use SoftDeletes;
protected $guarded = [];
protected $dates = ['deleted_at'];
public function product(){
return $this->hasMany('App\Product');
}
}
解决方案
如下所述,我应该使用groupBy
和havingRaw
来使查询正常工作,但事实证明这不是我在代码中唯一的问题
我将代码更改为:
$store = Store::with('session');
if ((int)$request->input('store-rating')>0) {
$store->whereHas('product',function($query) use($request) {
$rate = $request->input('product-rating');
$query->groupBy('rating')->havingRaw('AVG(rating) = '.$rate);
});
}
$thestore = $store->paginate(6);
return $thestore;
似乎我无法使用$store = new Store;
来启动我的模型查询
希望这可以帮助他人。
答案 0 :(得分:1)
尝试使用havingRaw
$query->grouBy('rating')->havingRaw('AVG(rating) = '.$rate);
不要忘记小组