Laravel Eloquent 关系 AVG 有
Laravel Eloquent Relationship AVG having
我有 store
table 与 product
table 相关,有 product.rating
(int) 1 到 5
我想根据我的 post 数据
找到平均产品评级为 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;
它总是 return 所有类似它的数据忽略我的 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;
来启动我的模型查询
希望这对其他人有帮助。
尝试使用 havingRaw
$query->grouBy('rating')->havingRaw('AVG(rating) = '.$rate);
别忘了分组依据
我有 store
table 与 product
table 相关,有 product.rating
(int) 1 到 5
我想根据我的 post 数据
找到平均产品评级为 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;
它总是 return 所有类似它的数据忽略我的 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;
来启动我的模型查询
希望这对其他人有帮助。
尝试使用 havingRaw
$query->grouBy('rating')->havingRaw('AVG(rating) = '.$rate);
别忘了分组依据