如何从原始对象创建 Eloquent 模型实例?

2021-12-26 00:00:00 php laravel eloquent

我需要使用 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..."); 

相关文章