扩展雄辩的类的构造函数 [英] Constructors on classes extending Eloquent
问题描述
我刚开始一个新的网站,我想利用雄辩。在播放我的数据库的过程中,我注意到,如果我在扩展雄辩的模型中包含了任何类型的构造函数,我将添加空行。例如,运行此播种器:
I just started a new website and I wanted to make use of Eloquent. In the process of seeding my database, I noticed that I would get empty rows added if I had included any kind of constructor on the model that extends eloquent. For example, running this seeder:
<?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'
)
);
}
}
将此作为我的团队类:
With this as my Team class:
<?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
只需将构造函数一起移除即可使播种机按预期方式工作。我正在做什么错误的构造函数?
Simply removing the constructor all together allows the seeder to work as expected. What exactly am I doing wrong with the constructor?
推荐答案
你必须调用 parent :: __ construct
使事情在这里工作,如果你看看 Eloquent
类的构造函数:
You have to call parent::__construct
to make things work here, if you look at the constructor of the 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);
}
启动
被调用,并且启动
属性被设置。我真的不知道这是做什么,但根据你的问题似乎相关:P
The boot
method is called and the booted
property is set. I don't really know what this is doing but depending on your problem it seems relevant :P
重构你的构造函数以获取属性
array并将其放在父构造函数中。
Refactor your constructor to get the attributes
array and put it to the parent constructor.
更新
这是需要的代码:
class MyModel extends Eloquent {
public function __construct($attributes = array()) {
parent::__construct($attributes); // Eloquent
// Your construct code.
}
}
这篇关于扩展雄辩的类的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!