Laravel种子多重关系

时间:2018-06-21 03:17:26

标签: php laravel laravel-seeding

我有3个模型:MemberInvoicePayment

这是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

如何获得所需的输出?

2 个答案:

答案 0 :(得分:0)

引荐-Factory CallbackssaveMany 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个支付模型