問題描述
我需要使用 Laravel 進行原始數據庫查詢:
I need to make a raw database query using Laravel:
$results = DB::select("SELECT * FROM members
INNER JOIN (several other tables)
WHERE (horribly complicated thing)
LIMIT 1");
我得到一個普通的 PHP StdClass 對象,其中包含成員表上的屬性字段.我想將其轉換為 Member(一個 Eloquent 模型實例),如下所示:
I get back a plain PHP StdClass Object with fields for the properties on the members table. I'd like to convert that to a Member (an Eloquent model instance), which looks like this:
use IlluminateDatabaseEloquentModel;
class Member extends Model {
}
我不知道該怎么做,因為會員沒有設置任何字段,而且我擔心我不會正確初始化它.實現這一目標的最佳方法是什么?
I'm not sure how to do it since a Member doesn't have any fields set on it, and I'm worried I will not initialize it properly. What is the best way to achieve that?
推薦答案
您可以嘗試將結果混合到模型對象中:
You can try to hydrate your results to Model objects:
$results = DB::select("SELECT * FROM members
INNER JOIN (several other tables)
WHERE (horribly complicated thing)
LIMIT 1");
$models = Member::hydrate( $results->toArray() );
或者你甚至可以讓 Laravel 從原始查詢中為你自動補水:
Or you can even let Laravel auto-hydrate them for you from the raw query:
$models = Member::hydrateRaw( "SELECT * FROM members...");
編輯
從 Laravel 5.4 hydrRaw 開始不再可用.我們可以使用 fromQuery 代替:
From Laravel 5.4 hydrateRaw is no more available. We can use fromQuery instead:
$models = Member::fromQuery( "SELECT * FROM members...");
這篇關于如何從原始對象創建 Eloquent 模型實例?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!