簡體   English   中英

我可以讓 Eloquent 模型加載與 sql JOIN 的關系而不是生成單獨的 sql 查詢嗎?

[英]Can I make an Eloquent model load a relationship with an sql JOIN instead of generating separate sql queries?

我是一名來自 CakePHP 的開發人員,並使用 Laravel 進行了我的第一個項目。 在 CakePHP 中,當我定義模型及其關系時,有一個選項可以在關系上設置連接策略: strategyjoinselect )。 默認情況下,它使用join ,當我加載相關模型時,它將通過添加JOIN語句在單個查詢中執行此操作。 您可以選擇使用select來生成單獨的查詢。

現在,當我在 Laravel 中使用預先加載時,例如:

$user = App\User::with(['articles'])->first();

這實際上會導致生成兩個查詢,一個用於獲取用戶記錄,另一個用於獲取相關文章。 這就像我在我的 CakePHP 模型中指定了select策略一樣。 但是,我想改用join策略,因此我可以執行諸如按相關表的列排序或過濾之類的操作。 我還沒有找到任何方法來做到這一點。 laravel/eloquent 中是否存在這樣的東西?

在 Laravel 中,使用連接獲取記錄非常簡單。 假設左連接這是一個示例代碼來獲取您的記錄:(您也可以使用任何最適合您需要的連接)

//assuming **title** and **description** as amongst the article fields
// and that you've passed the user's id as **$user_id**
//I've also assumed the articles table has a user id field **user_id** which has the corresponding user's id.
    $user = App\User::leftJoin('articles','users.id','articles.user_id')
->where('users.id',$user_id)
->select('users.*','artcles.title as title','articles.description as description')
->get();

暫無
暫無

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

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