Laravel convert an array to a model

做~自己de王妃 提交于 2020-01-02 00:43:24

问题


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.

thanks


回答1:


Try creating a new object and passing the array into the constructor

$topic = new Topic($array['topic']);



回答2:


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);



回答3:


Here is a generic way to do it, not sure if there is a Laravel-specific method -- but this is pretty simple to implement.

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.

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"
}



回答4:


It seems that you have data of an existing model there, so:

  1. First, you can use that array to fill only fillable (or not guarded) properties on your model. Mind that if there is no fillable or guarded array on the Topic model you'll get MassAssignmentException.
  2. Then manually assign the rest of the properties if needed.
  3. Finally use newInstance with 2nd param set to true 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).

.

$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?




回答5:


Look at these two available methods in L5 newInstance and newFromBuilder

e.g with(new static)->newInstance( $attributes , true ) ;




回答6:


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.




回答7:


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.

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.



来源:https://stackoverflow.com/questions/23661677/laravel-convert-an-array-to-a-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!