3
我已经store
表相关product
表,有product.rating
(INT)1至5Laravel雄辩关系AVG已经
我想找到商店,有平均产量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;
它总是返回像它忽略我的帖子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;
开始我的模型查询
希望这可以帮助别人。