laravel 如何从原始对象创建 Eloquent 模型实例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40855116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a Eloquent model instance from a raw Object?
提问by Kevin Burke
I need to make a raw database query using Laravel:
我需要使用 Laravel 进行原始数据库查询:
$results = DB::select("SELECT * FROM members
INNER JOIN (several other tables)
WHERE (horribly complicated thing)
LIMIT 1");
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:
我得到一个普通的 PHP StdClass 对象,其中包含成员表上的属性字段。我想将其转换为 Member(一个 Eloquent 模型实例),如下所示:
use Illuminate\Database\Eloquent\Model;
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?
我不知道该怎么做,因为会员没有设置任何字段,我担心我不会正确初始化它。实现这一目标的最佳方法是什么?
回答by Moppo
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() );
Or you can even let Laravel auto-hydrate them for you from the raw query:
或者你甚至可以让 Laravel 从原始查询中为你自动补水:
$models = Member::hydrateRaw( "SELECT * FROM members...");
EDIT
编辑
From Laravel 5.4 hydrateRawis no more available. We can use fromQueryinstead:
从 Laravel 5.4 开始,hydrRaw不再可用。我们可以使用fromQuery代替:
$models = Member::fromQuery( "SELECT * FROM members...");
回答by sleepless
You can simply init a new model:
您可以简单地初始化一个新模型:
$member = new App\Member;
Then you can assign the columns:
然后你可以分配列:
$member->column = '';
Or if all columns are mass assignable:
或者,如果所有列都可以批量分配:
$member->fill((array)$results);
Or have I misunderstood something?
还是我误解了什么?
回答by PlayMa256
You should definetly use Eloquentto perform that.
您应该明确地使用Eloquent来执行该操作。
You might declare the relations between the models, and use the where conditions.
您可以声明模型之间的关系,并使用 where 条件。
like:
喜欢:
Member::where(......)->get();
This will return an eloquent instance, and you can do whatever you need.
这将返回一个 eloquent 实例,你可以做任何你需要的事情。