2017-10-18 130 views
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'); 
    } 


} 

解決方案

如回答下面我應該使用groupByhavingRaw使查詢工作,但轉出,是不是我的唯一的問題代碼

我將密碼更改爲:

$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;開始我的模型查詢

希望這可以幫助別人。

回答

1

使用havingRaw

$query->grouBy('rating')->havingRaw('AVG(rating) = '.$rate); 

不要

忘記組嘗試