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;
開始我的模型查詢
希望這可以幫助別人。