我有三种型号: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我如何才能实现我想要的输出?
发布于 2018-06-21 11:51:42
参考- Factory Callbacks和saveMany function
现在,在您的MemberFactory.php,中添加以下内容
$factory->afterCreating(App\Member::class, function ($member, $faker) {
$member->invoice()->save(factory(App\Invoice::class)->make());
});在you 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();
}尚未测试,但应该可以工作:)
另外,我认为你的关系中不需要第二个参数。如果您使用的是单一命名法,该函数应该能够自动获得外键匹配。
发布于 2020-07-17 14:32:07
在you 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个付款模型
https://stackoverflow.com/questions/50959872
复制相似问题