簡體   English   中英

Laravel with()關系,如果記錄存在

[英]Laravel with() relationship if record exists

想象一下這個簡單的查詢。

User::with(['company' => function ($query) use($request) {
      $query->where('companies.name', 'like', '%'.$request->name.'%');
}])->get();

如果指定的公司不存在,則可能返回類似於以下集合的內容。

"data": [
        {
            "id": 1,
            "company": null
        }
    ],

即使公司值為null ,查詢也會運行並返回一個集合。 問題是在這種情況下我不希望返回記錄。 我只想要“公司”不為空的記錄。

如何在查詢中實現呢?

使用->with(["company" => function(){ ... }])不會基於邏輯過濾父User查詢,它只是限制了company關系中返回的內容。 要限制AND過濾器,您需要將->whereHas()->with()

User::with(["company"])->whereHas("company", function($query) use($request){
    $query->where("companies.name", "like", "%".$request->name."%");
})->get();

在某些情況下,你可能需要復制的邏輯->whereHas()在功能->with()但因為你是限制基於關系的查詢結果,你不應該。

暫無
暫無

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

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