我有3个模型:Member
,Invoice
和Payment
这是Member
模型:
class Member extends Model
{
public function invoice()
{
return $this->hasOne(Invoice::class);
}
}
在Invoice
模型中:
class Invoice extends Model
{
public function member()
{
return $this->belongsTo(Member::class, 'member_id');
}
public function payments()
{
return $this->hasMany(Payment::class, 'invoice_id');
}
}
最后,Payment
模型:
class Payment extends Model
{
public function invoice()
{
return $this->belongsTo(Invoice::class, 'invoice_id');
}
}
现在,在我的播种机中,我想为每个成员的每个发票创建付款:
public function run()
{
factory(Member::class, 100)->create()->each(function ($m) {
$m->invoice()->save(factory(App\Invoice::class)->create()->each(function ($i) {
$i->payments()->save(factory(App\Payment::class)->make());
}));
});
}
但是当我尝试播种时,它返回一个错误:
Symfony\Component\Debug\Exception\FatalThrowableError : Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, boolean given
如何获得所需的输出?
答案 0 :(得分:0)
引荐-Factory Callbacks和saveMany function
现在,在您的 MemberFactory.php 中添加此
$factory->afterCreating(App\Member::class, function ($member, $faker) {
$member->invoice()->save(factory(App\Invoice::class)->make());
});
在您的 InvoiceFactory.php 中,添加此
$factory->afterMaking(App\Invoice::class, function ($invoice, $faker) {
$invoice->payments()->saveMany(factory(App\Payment::class, 5)->make());
});
最后,在您的run()
函数中,执行
public function run()
{
factory(Member::class, 100)->create();
}
尚未测试,但应该可以工作:)
此外,我认为您在关系中不需要第二个参数。如果您使用的是单数术语,则该功能应该能够自动获得外键匹配。
答案 1 :(得分:0)
在您的seed / Databaseeder.php中(在Laravel 7中进行了测试)
public function run()
{
factory(App\Member::class, 100)->create()->each(function ($m) {
// Seed the relation with one address
$invoice = factory(App\Invoice::class)->make();
$payments = factory(App\Payment::class,5)->make();
$m->invoice()-save($invoice);
$invoice->payments()->saveMany($payments)
});
}
run
函数代表创建100个成员模型实例,为每个成员模型创建一个发票模型,为每个发票创建5个支付模型