簡體   English   中英

Laravel:如何從查詢結果中獲取模型?

[英]Laravel: How to get Models out of query results?

假設我有一個查詢,除其他外,返回用戶 ID,這個查詢是使用DB::table()...構建的DB::table()...而不是使用模型,因此,結果,我得到了一個包含數組的集合行,是這樣的:

user_id | calculated_data
--------+----------------
      1 |     123
      2 |     111
      3 |     222
    ... |     ...

假設我將此集合存儲在$data變量上,當然,如果我執行foreach ($data as $d) { $d->user_id ... }將起作用。

但我希望這個查詢返回更像 ORM 所做的事情,所以代替user_id s,返回 User 模型,這樣我就可以做,例如, $data->user->name

這甚至可以做到嗎? 如果是這樣,如何?

您可以使用hydrate()函數,它接受一個stdClass對象array (甚至關聯數組 AFAIR)作為輸入並返回 Eloquent Eloquent Modelscollection ,因此您可以執行以下操作:

$result = DB::table('users')->take(10)->get();
$users = App\User::hydrate($result->all()); 

您甚至可以使用fromQuery()函數直接從原始查詢中獲取fromQuery() Eloquent Models的集合,即:

$users = App\User::fromQuery('SELECT * FROM users WHERE id > ?', [2])

更新:如果在您的集合中沒有所有字段來對模型進行hydrate ,您可以使用一個查詢預加載您需要的所有用戶並修改您的collection ,即:

$users = App\User::find($data->pluck('user_id'));
$data->transform(function($item) use($users) {
            $item->user = $users->where('id', $item->user_id)->first()
            return $item;
        }); 

您需要使用 Eloquent 以“ORM 方式”調用 value 我沒有找到與 ORM 相關的查詢構建器的任何相關內容。

你可以這樣做:

$flights = App\Flight::all(); 

foreach ($flights as $flight) {
    echo $flight->name;
}

在 ORM 方式中,您將獲得這樣的用戶:

foreach ($flights as $flight) {
    echo $flight->user->name;
}

當然,您需要設置正確的關系。

// initial query will return collection of objects
$query = DB::table('user_something')
   ->join('users', 'users.id', 'user_something.user_id');

// You could cast it to the model query, by using fromSub.
// Make sure to alias a subquery same as the model's name,
// otherwise it would not be able to parse models data
User::fromSub($query, 'users');

// The most robust way is to get table name from the model
User::fromSub($query, User::make()->getTable());

暫無
暫無

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

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