我正在尝试使用新的Laravel 5.1模型工厂来播放我的应用程序表。
使用http://laravel.com/docs/5.1/seeding#using-model-factories上的信息我构建了这样的内容:
// Account Model
class Account extends Model
{
public function contacts()
{
return $this->hasMany('App\Contact');
}
// Contact Model
class Contact extends Model
{
public function account()
{
return $this->belongsTo('App\Account');
}
// Account table seeder
$accounts = factory(App\Account::class(), 25)->create()->each(function($u) {
$u->contacts()->save(factory(App\Contact::class)->make());
问题是外键永远不会被正确设置(应该传递给account_id
表的相应contact
没有被传递。
我尝试像这样手动设置account_id
:
$u->contacts()->save(factory(App\Contact::class)->make([
'account_id' => $u->id,
]);
但是这失败了,无论如何,在文档中没有提到它。
有没有人成功使用过这个?
答案 0 :(得分:1)
显然,因为我使用了非标准的主键名称,所以我必须提供本地和外键列。
因为我在迁移中指定了主键,所以我认为Laravel会接受它。
为了完成这项工作,您必须在模型中执行以下操作:
// Account Model
class Account extends Model
{
public function contacts()
{
return $this->hasMany('App\Contact', 'account_id', 'account_id');
}
一旦我这样做,播种按预期工作。