Laravel 将数组转换为模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23661677/
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 convert an array to a model
提问by Gagan
i have an array as follows
我有一个数组如下
'topic' =>
array (
'id' => 13,
'title' => 'Macros',
'content' => '<p>Macros. This is the updated content.</p>
',
'created_at' => '2014-02-28 18:36:55',
'updated_at' => '2014-05-14 16:42:14',
'category_id' => '5',
'tags' => 'tags',
'referUrl' => '',
'user_id' => 3,
'videoUrl' => '',
'useDefaultVideoOverlay' => 'true',
'positive' => 0,
'negative' => 1,
'context' => 'macros',
'viewcount' => 60,
'deleted_at' => NULL,
)
I would like to use this array and convert/cast it into the Topic Model . Is there a way this can be done.
我想使用这个数组并将其转换/转换为 Topic Model 。有没有办法做到这一点。
thanks
谢谢
回答by Laurence
Try creating a new object and passing the array into the constructor
尝试创建一个新对象并将数组传递给构造函数
$topic = new Topic($array['topic']);
回答by Liquinaut
For creating models from a single item array:
从单个项目数组创建模型:
$Topic = new Topic();
$Topic->fill($array);
For creating a collection from an array of items:
从一组项目创建一个集合:
$Topic::hydrate($result);
回答by Sam
Here is a generic way to do it, not sure if there is a Laravel-specific method -- but this is pretty simple to implement.
这是一个通用的方法,不确定是否有 Laravel 特定的方法——但这很容易实现。
You have your Topic
class with its properties, and a constructor that will create a new Topic
object and assign values to its properties based on an array of $data
passed as a parameter.
您拥有您的Topic
类及其属性,以及一个构造函数,该构造函数将创建一个新Topic
对象并根据$data
作为参数传递的数组为其属性分配值。
class Topic
{
public $id;
public $title;
public function __construct(array $data = array())
{
foreach($data as $key => $value) {
$this->$key = $value;
}
}
}
Use it like this:
像这样使用它:
$Topic = new Topic(array(
'id' => 13,
'title' => 'Marcos',
));
Output:
输出:
object(Topic)#1 (2) {
["id"]=>
int(13)
["title"]=>
string(6) "Marcos"
}
回答by Jarek Tkaczyk
It seems that you have data of an existing model there, so:
您似乎在那里拥有现有模型的数据,因此:
- First, you can use that array to fill only
fillable
(or notguarded
) properties on your model. Mind that if there is nofillable
orguarded
array on theTopic
model you'll get MassAssignmentException. - Then manually assign the rest of the properties if needed.
- Finally use
newInstance
with 2nd param set totrue
to let Eloquent know it's existing model, not instantiate a new object as it would, again, throw an exception upon saving (due to unique indexes constraints, primary key for a start).
- 首先,您可以使用该数组仅填充
fillable
(或不填充guarded
)模型上的属性。请注意,如果模型上没有fillable
或guarded
数组,Topic
您将收到 MassAssignmentException。 - 然后根据需要手动分配其余的属性。
- 最后使用
newInstance
2nd param 设置为true
让 Eloquent 知道它是现有模型,而不是实例化一个新对象,因为它会再次在保存时抛出异常(由于唯一索引约束,主键开始)。
.
.
$topic = with(new Topic)->newInstance($yourArray, true);
$topic->someProperty = $array['someProperty']; // do that for each attribute that is not fillable (or guarded)
...
$topic->save();
To sum up, it's cumbersome and probably you shouldn't be doing that at all, so the question is: Why you'd like to do that anyway?
总而言之,这很麻烦,而且您可能根本不应该这样做,所以问题是:您为什么还要这样做?
回答by Raja Khoury
Look at these two available methods in L5 newInstanceand newFromBuilder
看看 L5 newInstance和newFromBuilder这两个可用的方法
e.g with(new static)->newInstance( $attributes , true ) ;
例如 with(new static)->newInstance( $attributes , true ) ;
回答by Rockin4Life33
I came across this question looking for something else. Noticed it was a bit outdated and I have another way that I go about handling the OPs issue. This might be a known way of handling the creation of a model from an array with more recent versions of Laravel.
我在寻找其他东西时遇到了这个问题。注意到它有点过时了,我还有另一种处理 OP 问题的方法。这可能是一种已知的处理从具有更新版本的 Laravel 的数组创建模型的方法。
I add a generic constructor to my class/model
我向我的类/模型添加了一个通用构造函数
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
}
Then when I want to create a new instance of the model from an array I make a call like this
然后,当我想从数组创建模型的新实例时,我会像这样调用
$topic = new Topic($attrs);
// Then save it if applicable
$topic->save(); // or $topic->saveOrFail();
I hope someone finds this helpful.
我希望有人觉得这有帮助。
回答by Jonathan
I would likely create the new instance of the object and then build it that way, then you can actually split some useful reusable things or defaults into the model otherwise what's the point in pushing an array into a model and doing nothing with it - very little besides for normalization.
我可能会创建对象的新实例,然后以这种方式构建它,然后您实际上可以将一些有用的可重用事物或默认值拆分到模型中,否则将数组推入模型而不对其进行任何操作有什么意义 - 很少除了规范化。
What I mean is:
我的意思是:
$topic = new Topic();
$topic->id = 3489;
$topic->name = 'Test';
And the model would simply be a class with public $id;
. You can also set defaults so if you had like resync_topic or whatever property, you can set it as 0 in the model rather than setting 0 in your array.
并且该模型只是一个带有public $id;
. 您还可以设置默认值,因此如果您喜欢 resync_topic 或任何属性,则可以在模型中将其设置为 0,而不是在数组中设置为 0。