沃梦达 / 编程问答 / php问题 / 正文

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

How to create a Eloquent model instance from a raw Object?(如何从原始对象创建 Eloquent 模型实例?)

本文介绍了如何从原始对象创建 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..."); 

这篇关于如何从原始对象创建 Eloquent 模型实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何从原始对象创建 Eloquent 模型实例?

基础教程推荐