我刚刚启动了一个新网站,我想使用 Eloquent。在为数据库播种的过程中,我注意到,如果我在扩展 eloquent 的模型上包含任何类型的构造函数,则会添加空行。例如,运行此播种器:
<?php
class TeamTableSeeder extends Seeder {
public function run()
{
DB::table('tm_team')->delete();
Team::create(array(
'city' => 'Minneapolis',
'state' => 'MN',
'country' => 'USA',
'name' => 'Twins'
)
);
Team::create(array(
'city' => 'Detroit',
'state' => 'MI',
'country' => 'USA',
'name' => 'Tigers'
)
);
}
}
将此作为我的团队课程:
<?php
class Team extends Eloquent {
protected $table = 'tm_team';
protected $primaryKey = 'team_id';
public function Team(){
// null
}
}
产生这个:
team_id | city | state | country | name | created_at | updated_at | deleted_at
1 | | | | | 2013-06-02 00:29:31 | 2013-06-02 00:29:31 | NULL
2 | | | | | 2013-06-02 00:29:31 | 2013-06-02 00:29:31 | NULL
只需将构造函数全部删除即可让播种器按预期工作。我对构造函数到底做错了什么?
你必须打电话parent::__construct
为了让事情在这里工作,如果你看看的构造函数Eloquent
class:
public function __construct(array $attributes = array())
{
if ( ! isset(static::$booted[get_class($this)]))
{
static::boot();
static::$booted[get_class($this)] = true;
}
$this->fill($attributes);
}
The boot
方法被调用并且booted
属性已设置。我真的不知道这是做什么的,但根据你的问题,它似乎是相关的:P
重构你的构造函数以获得attributes
数组并将其放入父构造函数中。
Update
这是所需的代码:
class MyModel extends Eloquent {
public function __construct($attributes = array()) {
parent::__construct($attributes); // Eloquent
// Your construct code.
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)