在州内创建工厂并在 Laravel 中获取其自身的 ID

Creating a factory inside the state and getting the id of itself in Laravel

我正在开发 Laravel 应用程序。我在我的应用程序中使用工厂,特别是用于单元测试和设置它们,但我在设置带有状态的工厂时遇到问题。这是我的数据库结构:

出价

id, amount, created_at, updated_at, user_id

那我还有一个模型如下:

投标记录

id, bid_status, created_at, updated_at, bid_id

数据库结构非常简单。问题是 BidLog 只会在 Bid 的事件侦听器中创建。它仅在 Bid 存在时存在。它基本上是投标的状态。所以当我为 BidLog 设置工厂时,我设置了这样的东西。

BidLogFactory.php

$factory->define(BidLog::class, function (Faker $faker) {
    $bid = Bid::inRandomOrder()->first();
    return [
        'bid_id' => $bid->id,
        'bid_status' => 'open'//Bid factory will override this value
    ];
});

然后我像这样设置 BidFactory 的状态。

$factory->state(Bid::class, 'open', function ($faker) {
    $bidLog = factory(BidLog::class)->create([
       'bid_status' => 'open',
       'bid_id' => //how can I get the bid id here?
    ]);
    return [
       'updated_at' => now()
    ];
});

问题是如何在状态回调函数中获取Bid id?或者我该如何设置?

passing using callback function (closure)

这样使用

$factory->state(Bid::class, 'open', function ($faker) {
    $bidLog = factory(BidLog::class)->create([
       'bid_status' => 'open',
       'bid_id' => function(){
           return   Bid::inRandomOrder()->first()->id;
        }
    ]);
    return [
       'updated_at' => now()
    ];
});

在这里使用 afterCreatingState 方法(我认为)更多 see

$factory->state(Bid::class, 'open', [])
        ->afterCreatingState(Bid::class,'open',function($bid,$faker) { 
              factory(BidLog::class)->create([
                  'bid_status' => 'open',
                  'bid_id' => $bid->id
             ]);
         });

我遇到了同样的问题所以,我分享示例代码

假设,我有收入table用于保存总收入&还有income_records另一个table 表示收入的详细数据 table 数据

收入Table

id, date, amount, created_at, updated_at

income_records

id, income_id , etc... many more other data fields

现在,我想使用Laravel工厂输入假测试数据,那么你可以像下面这样从收入table的主键中获取income_id命名的外键

这里我有 Income 模型 income_table & IncomeRecord 模型 income_recordstable

现在我在 DatabaseSeeder class 文件的 运行() 函数中编写下面的代码

 <?php 
  $incomes = Income::factory(10)
            ->create(); // fake plot's Income create for companies
 
  $incomes->each(function($income) {
        IncomeRecord::factory()
                 ->state([
                        'income_id' => $income->id,
                 ])->create();
  });
 ?>

希望本文对您有所帮助...

Note:- I used Laravel 8 version... it may be will not works for below versions. So, Please Test it for other versions & if its works then Please edit my answer about Laravel version details