Laravel将数组转换为模型

时间:2014-05-14 17:50:06

标签: laravel laravel-4

我有一个数组如下

      '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,
  )

我想使用此数组并将其转换/转换为主题模型。有没有办法可以做到这一点。

感谢

7 个答案:

答案 0 :(得分:15)

从单个项目数组创建模型:

public String getChildrenNames(List<Person> childname) {

从一系列项目创建集合:

$Topic = new Topic();
$Topic->fill($array);

答案 1 :(得分:14)

尝试创建一个新对象并将数组传递给构造函数

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

答案 2 :(得分:3)

这是一种通用的方法,不确定是否有特定于Laravel的方法 - 但这很容易实现。

您的Topic类包含其属性,以及一个构造函数,它将创建一个新的Topic对象,并根据作为参数传递的$data数组为其属性赋值

class Topic
{

    public $id;
    public $title;

    public function __construct(array $data = array())
    {
        foreach($data as $key => $value) {
            $this->$key = $value;
        }
    }

}

像这样使用:

$Topic = new Topic(array(
    'id' => 13,
    'title' => 'Marcos',
));

输出:

object(Topic)#1 (2) {
  ["id"]=>
  int(13)
  ["title"]=>
  string(6) "Marcos"
}

答案 3 :(得分:2)

似乎你有现有模型的数据,所以:

  1. 首先,您可以使用该数组仅填充模型上的fillable(或非guarded)属性。请注意,如果fillable模型上没有guardedTopic数组,您将获得MassAssignmentException。
  2. 然后根据需要手动分配其余属性。
  3. 最后使用newInstance将第二个参数设置为true让Eloquent知道它的现有模型,而不是实例化一个新对象,因为它会再次在保存时抛出异常(到期)独特的索引约束,开始的主键)。
  4. $topic = with(new Topic)->newInstance($yourArray, true);
    $topic->someProperty = $array['someProperty']; // do that for each attribute that is not fillable (or guarded)
    ...
    $topic->save();
    

    总而言之,它很麻烦,可能你根本就不应该这样做,所以问题是:为什么你还想这样做?

答案 4 :(得分:0)

我可能会创建对象的新实例,然后以这种方式构建它,然后你可以实际上将一些有用的可重用事物或默认值分解到模型中,否则将数组推入模型并对其无效的重点是什么 - 除了标准化之外很少。

我的意思是:

$topic = new Topic();
$topic->id = 3489;
$topic->name = 'Test';

模型只是一个public $id;的类。您也可以设置默认值,这样如果您有resync_topic或其他属性,可以在模型中将其设置为0,而不是在数组中设置0。

答案 5 :(得分:0)

在L5 newInstancenewFromBuilder

中查看这两种可用方法

例如with(new static)->newInstance( $attributes , true ) ;

答案 6 :(得分:0)

我遇到了这个问题,正在寻找其他东西。注意这有点过时了,我还有另一种方式来处理OP问题。这可能是处理使用较新版本的Laravel从数组创建模型的已知方法。

  

我在类/模型中添加了通用构造函数

public function __construct(array $attributes = [])
{
    parent::__construct($attributes);
}
  

然后,当我想从数组中创建模型的新实例时,我会像这样进行调用

$topic = new Topic($attrs);
// Then save it if applicable
$topic->save(); // or $topic->saveOrFail();

我希望有人能对此有所帮助。