种子程序加载雄辩数据时出现array_merge错误


array_merge error during seeder whilst loading eloquent data

简介

我遇到了一个关于laravel-5的非常令人困惑的问题。从本质上讲,我所拥有的是许多种子程序,它们从JSON文档加载数据,并使用雄辩的方法插入到数据库中——这很好。

我有一个最后的播种器,它循环通过一些数据,在这个循环中,我加载了一个记录,但当我试图访问数据时,我收到了以下错误:

  [ErrorException]                            
    array_merge(): Argument #1 is not an array

种子狙击手

foreach ($data as $country => $states) {
    $countryId = Country::where('iso2_code', $country)->first()->pluck('id');
    dd($countryId); // ErrorException
    array_walk($states, function (&$value) use ($countryId) {
        $value = ['country_id' => $countryId, 'name' => $value];
    });
    State::insert($states);
}

这个错误令人困惑的部分是,如果我不使用Eloquent,我的问题就解决了,根据:

foreach ($data as $country => $states) {
    $countryId = DB::table((new Country)->getTable())
        ->select('id')
        ->where('iso2_code', $country)
        ->first();
    dd($countryId->id); // Works.
    array_walk($states, function (&$value) use ($countryId) {
        $value = ['country_id' => $countryId, 'name' => $value];
    });
    State::insert($states);
}

为什么DB按预期工作,而Eloquent触发了一些array_merge错误?

解决方案

在我的情况下,我在我的模型上设置了protected $dates = false。通常根据文档,我应该使用public $timestamps = falseprotected $dates = array();