簡體   English   中英

Laravel Eloquent Relationship AVG有

[英]Laravel Eloquent Relationship AVG having

我有與product表相關的store表,它有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');
    }


}

如下所述,我應該使用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; 開始我的模型查詢

希望這可以幫助別人。

嘗試使用havingRaw

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

別忘了小組

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM