Laravel,如何将对象转换为新的 Eloquent 模型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40527967/
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
Laravel, how cast object to new Eloquent Model?
提问by koalaok
I get via Request a Json Object. I clearly parse this object in order to check if it may fit the destination model.
我通过请求一个 Json 对象获得。我清楚地解析了这个对象,以检查它是否适合目标模型。
Instead of assigning property by property. Is there a quick way to populate the model with the incoming object?
而不是按财产分配财产。有没有一种快速的方法来用传入的对象填充模型?
回答by Martin Bean
If you have an array of arrays, then you can use the hydrate()
method to cast it to a collection of the specified model:
如果您有一个数组数组,那么您可以使用该hydrate()
方法将其强制转换为指定模型的集合:
$records = json_decode($apiResult, true);
SomeModel::hydrate($records);
If you just have a single record, then you can just pass that array to the model's constructor:
如果您只有一条记录,那么您可以将该数组传递给模型的构造函数:
$model = new SomeModel($record);
回答by Paul
Just pass your object casted to array as Model constructor argument
只需将您的对象作为模型构造函数参数传递给数组
$model = new Model((array) $object);
Internally this uses fill()
method, so you may first need to add incoming attributes to $fillable
property or first create model and then use forceFill()
.
这在内部使用fill()
方法,因此您可能首先需要将传入属性添加到$fillable
属性或首先创建模型然后使用forceFill()
.
回答by Saumya Rastogi
You can use Mass Assignmentfeature of Laravel,
您可以使用Laravel 的批量分配功能,
You model would look like this:
您的模型将如下所示:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'phone'];
}
And the process of populating the Model would be like this:
填充模型的过程是这样的:
// This would be your received json data converted to array
// use 'json_decode($json, true)' to convert json data to array
$json_arr = [
'name' => 'User Name',
'email' => '[email protected]',
'phone' => '9999999999'
];
$user = new \App\User($json_arr);
Hope this helps!
希望这可以帮助!
回答by Giedrius Kir?ys
You should convert that object to array and use fill($attributes)
method.
您应该将该对象转换为数组并使用fill($attributes)
方法。
As method name says, it will fill object with provided values. Keep in mind that it will not persist to database, You have to fire save()
method after that.
Or if You want to fill and persist in one method - there is create($attributes)
which runs fill($attributes)
and save()
under the hood.
正如方法名称所说,它将用提供的值填充对象。请记住,它不会持久保存到数据库中,之后您必须触发save()
方法。
或者如果你想以填补在一个方法坚持-有create($attributes)
它运行fill($attributes)
和save()
引擎盖下。