簡體   English   中英

Laravel: eloquent orderBy hasOne 關系列使用 with 和 whereHas

[英]Laravel: eloquent orderBy hasOne relation column using with and whereHas

我有一個帶有 hasOne 關系方法getCompany()的 model Product

public function getCompany(){
    return $this->hasOne(Company::class, 'id', 'company_id');
}

我需要檢索按getCompany.rate排序的Product集合

我的方法


$products = Product::with('getCompanyName', 'getCompany')
    ->whereHas('getCompany', function ($query) {
        return $query->where('status_shop_id', '=', 2);
    })
    ->whereHas('getCompany', function ($query) {
        return $query->where('status', '=', 1);
    })
    ->where('name', 'Like', "%$text%")
    ->whereStatus(1)
    ->whereTypeId(1)
    ->orderBy('rate', 'desc')
    ->limit(5)
    ->get();

失敗:

SQLSTATE [42S22]:未找到列:1054 未知列“getCompany.rate”在“訂單子句”中

我試圖在收集后對其進行排序

return $products->sortBy('getCompany.rate');

但這根本沒有排序

如果要根據關系的內容進行排序,則必須事后進行 這些關系在主 model 中顯示為對象,並單獨獲取,因此您不能指望在數據庫級別執行此操作。

也沒有必要重復whereHas兩次; 您可以將兩個條件都放在回調中。

$products = Product::with('getCompanyName', 'getCompany')
    ->whereHas('getCompany', function ($query) {
        $query->where('status_shop_id', '=', 2)->where('status', '=', 1);
    })
    ->where('name', 'Like', "%$text%")
    ->whereStatus(1)
    ->whereTypeId(1)
    ->limit(5)
    ->get();
$sorted = $products->sortByDesc('getCompany.rate');

一個簡單的測試將證明這很有效:

$coll = collect([
    ["name" => "item 1", "relation" => ["size" => 23]],
    ["name" => "item 2", "relation" => ["size" => 16]],
    ["name" => "item 3", "relation" => ["size" => 15]],
    ["name" => "item 4", "relation" => ["size" => 42]],
]);
dump($coll->sortBy('relation.size'));

Output:

=> Illuminate\Support\Collection {#12167
     all: [
       2 => [
         "name" => "item 3",
         "relation" => [
           "size" => 15,
         ],
       ],
       1 => [
         "name" => "item 2",
         "relation" => [
           "size" => 16,
         ],
       ],
       0 => [
         "name" => "item 1",
         "relation" => [
           "size" => 23,
         ],
       ],
       3 => [
         "name" => "item 4",
         "relation" => [
           "size" => 42,
         ],
       ],
     ],
   }

如果您想根據另一個表的列進行排序,最好使用連接。

@user3532758 你能告訴我嗎?

嘗試這樣的事情:

DB::table('products') //can use Product::join(...) as well and can attach your relationships too, just make sure necessary ids are in the select statement
->join('companies', 'products.id', '=', 'companies.product_id')
->select('products.*', 'companies.name', 'companies.rate')
->orderBy('companies.rate', 'desc')
->get();

暫無
暫無

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

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