亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

調用字符串上的成員函數 addEagerConstraints()

調用字符串上的成員函數 addEagerConstraints()

PHP
Cats萌萌 2022-07-29 16:27:09
我想計算嵌套變形關系列的平均值。模型功能public function trader_ratings(){    return $this->morphMany(TraderRatings::class, 'rateable')        ->select('rateable_id', 'rateable_type', 'rating')        ->avg('rating');}延遲加載的控制器$user = auth('api')->user();$user_id = $user->id;$customer_classes = CustomerClassBooking::with([    'trader_class',    'trader_class.trader_ratings',    'vendor',])    ->where('customer_id', $user_id)    ->where('status', 'Accepted-paid')    ->get();它不是計算錯誤,avg而是給出錯誤。
查看完整描述

2 回答

?
白衣非少年

TA貢獻1155條經驗 獲得超0個贊

因為with()需要得到關系。addEagerConstraints來自源代碼。當您使用即時加載時,您的關系構建器將調用addEagerConstraints.


但是,您的關系方法是返回字符串(的結果avg())而不是變形關系。所以會發生錯誤。


你可以改變你的方法,如:


public function trader_ratings()

{

    return $this->morphMany(TraderRatings::class, 'rateable')->select('*', DB::raw('AVG(rating) AS avg_rating'));

}


查看完整回答
反對 回復 2022-07-29
?
qq_笑_17

TA貢獻1818條經驗 獲得超7個贊

該錯誤清楚地表明 trader_ratings 已經計算了平均值,并且不再是您急切加載所需的構建器實例。所以可能會做一些如下的事情,(沒有測試代碼,只是從我的頭頂)


public function trader_ratings()

{

  return $this->morphMany(TraderRatings::class, 'rateable')->select('rateable_id','rateable_type','rating');

 }



// Then


$customer_classes = CustomerClassBooking::with([

         'trader_class',

         'trader_class.trader_ratings' => function($query`){

            $query->avg('rating)

         },


        ,'vendor'])-> // rest of query


查看完整回答
反對 回復 2022-07-29
  • 2 回答
  • 0 關注
  • 149 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號