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

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

Laravel 訂單集合基于一對多關聯關系的屬性

Laravel 訂單集合基于一對多關聯關系的屬性

PHP
蕭十郎 2023-04-21 13:55:59
我有一個名為 Business 的模型(包含列描述、名稱、視圖等),它與模型“Rating”具有一對多關系。我想查詢我的業務模型,以便它返回一個結果,檢查名稱或描述中是否存在搜索字符串,并首先按評級最高的業務排序,然后再查看業務。我已經為搜索查詢編寫了代碼。在下面找到:$business = Business::with('images')    ->where('isActive', true)    ->where(function ($q) use ($query) {        $q->where('name', 'LIKE', '%' . $query . '%')            ->orWhere('description', 'LIKE', '%' . $query . '%');    })->get();我知道我可以像這樣獲取企業的平均評分:$averageRating = Rating::where('business_id', $id)->avg('rating');$business = Business::with(['images'])->get();foreach ($business as $item) {    $item["rating"] = floor($averageRating);}那么,我如何根據最高收視率排序,然后是最高瀏覽量?
查看完整描述

3 回答

?
慕桂英3389331

TA貢獻2036條經驗 獲得超8個贊

您可以使用子查詢選擇:


business = Business::with('images')

? ? ? ? ->where('isActive', true)

? ? ? ? ? ? ? ? ? ? ->where(function ($q) use ($query){

? ? ? ? ? ? ? ? ? ? ? ? $q->where('name', 'LIKE','%'.$query.'%')->orWhere('description', 'LIKE','%'.$query.'%');

? ? ? ? ? ? ? ? ? ? })

->orderByDesc(['topRating' => Rating::select('rating')

? ? ->whereColumn('business_id', 'businesses.id')

? ? ->orderBy('rating', 'desc')

? ? ->limit(1)])

->get();

請確保設置業務表名稱而不是“業務”

查看完整回答
反對 回復 2023-04-21
?
吃雞游戲

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

為此,您必須手動加入表格:


$business = Business::with('images')

    ->join('rating_table', 'rating_table.business_id', '=', 'business_table.id')

    ->where('isActive', true)

    ->where(function ($q) use ($query){

        $q->where('name', 'LIKE','%'.$query.'%')

            ->orWhere('description', 'LIKE','%'.$query.'%');

    })

    ->orderBy('rating_table.value', 'DESC')

    ->get();

經過多次嘗試,無法使用 Eloquent 按他們的關系對“父”進行排序,您可以在關系內部進行排序,僅此而已。


查看完整回答
反對 回復 2023-04-21
?
躍然一笑

TA貢獻1826條經驗 獲得超6個贊

我相信你必須像這樣使用連接:


$business = Business::select([

    'businesses.*', \DB::raw('AVG(ratings.rating) as avg_rating')

  ])

  ->join('ratings', 'businesses.id', '=', 'ratings.business_id')

  ->orderBy('ratings.avg_rating', 'DESC')

  ->get();

未測試


查看完整回答
反對 回復 2023-04-21
  • 3 回答
  • 0 關注
  • 419 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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