php - 播种 - 具有 3 级关系的 Laravel 模型工厂

标签 php laravel

我目前正在构建一个系统来管理我的出租特性。我有一个保存属性的模型,每个属性可以有多个租赁。

为了对租赁进行计费,我有一个名为 Invoice 的模型,它属于 Lease。此外,一张发票将有许多 InvoiceLine

//Property.php
public function leases()
{
        return $this->hasMany(Lease::class);
}

//Lease.php
public function invoices(){
        return $this->hasMany(Invoice::class);
}

//Invoice.php
public function lines()
{
        return $this->hasMany(InvoiceLine::class);
}

我正在尝试为此设置设置种子:

Property::factory()
   ->count(1)
   ->has(
   Lease::factory()
      ->count(2)
      ->hasInvoices(1) // Where to create "Invoice Lines"?
   )
   ->create();

现在,如您所见,在运行此播种时,我仅创建发票 - 但没有发票行。

如何使用属于租赁的发票行生成发票?

作为引用,这是工厂类查找发票和发票行的方式:

//InvoiceFactory.php
return [
    'tax' => 0,
    'total' => 25000,
];
//InvoiceLineFactory.php
return [
    'description' => 'Rent for April',
    'tax' => 0,
    'total' => 25000,
];

最佳答案

您可以简单地使用 has 而不是 hasInvoices

Property::factory()->has(
    Lease::factory()->has(
        Invoice::factory()->has(
            InvoiceLine::factory()->count(3),
        )->count(1)
    )->count(2)
)->count(1)->create();

关于php - 播种 - 具有 3 级关系的 Laravel 模型工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67025787/

相关文章:

codeigniter - 如何使 laravel 比 codeigniter 更快的页面加载

php - 在 mysql select 语句中使用两个 php 变量

php - 在 PHP 函数中查询数据库

php - WooCommerce Checkout url hook - 根据产品类别更改条件

php - Laravel auth 系统可以使用现有数据库吗?

php - 将 laravel jenssegers 连接到 mongodb atlas 集群

Laravel created_at 格式化

forms - laravel 表单模型绑定(bind) - 日期格式

php - 从同一 WordPress 数据库中的表中获取所有相关数据

php - 我的 sef 链接如何使用 .htaccess