If conditions in Factory Laravel
我创建了一个工厂文件来创建假元素来测试我的网络系统。我想知道是否有办法根据之前创建的元素的值创建一个 if 条件来创建另一个元素。
它适用于简单的模型,但对于那些需要元素之间关系的模型,我找不到方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <?php use Faker\\Generator as Faker; $factory->define(App\\ItemDoEstoque::class, function (Faker $faker) { return [ 'origem' => $faker->randomElement(['Fabrication','Raw','Resale','Cleaning','Others']), 'quantity' => rand(100,999), 'batch' => $faker->ean13, 'date_fabrication' => $faker->date($format = 'Y-m-d', $max = 'now'), 'date_validate' => $faker->date($format = 'Y-m-d', $max = 'now'), 'stock_id' => function () { return App\\Stock::inRandomOrder()->first()->id; }, 'product_sell_id' => function () { return App\\ProductSell::inRandomOrder()->first()->id; }, 'product_buy_id' => function () { return App\\ProductBuy::inRandomOrder()->first()->id; }, 'supplier_id' => function () { return App\\Supplier::inRandomOrder()->first()->id; }, 'buyer_id' => function () { return App\\Buy::inRandomOrder()->first()->id; }, 'reservation_id' => function () { return App\\Fabrication::inRandomOrder()->first()->id; }, ]; }); |
我的期望是:
如果 origem = Fabrication,则 batch、product_sell_id、quantity 和 date_fabrication 不会为空,但其余部分必须为空。
如果 origem = Raw,则:
1 2 3 4 5 6 7 8 9 10 11 | 'origem' => Raw, 'quantity' => NOT NULL, 'batch' => NULL, 'date_fabrication' => NULL, 'date_validate' => NOT NULL, 'stock_id' => NOT NULL, 'product_sell_id' => NULL, 'product_buy_id' => NOT NULL, 'supplier_id' => NOT NULL}, 'buyer_id' => NULL, 'reservation_id' => NOT NULL |
如果 origem = 制造,那么:
1 2 3 4 5 6 7 8 9 10 11 | 'origem' => Fabrication, 'quantity' => NOT NULL, 'batch' => NOT NULL, 'date_fabrication' => NOT NULL, 'date_validate' => NOT NULL AND BIGGER THAN date_fabrication, 'stock_id' => NOT NULL, 'product_sell_id' => NOT NULL, 'product_buy_id' => NULL, 'supplier_id' => NULL}, 'buyer_id' => NOT NULL, 'reservation_id' => NULL |
等等。
所以请知道如何制作这样的条件:
如果 \\'origem\\' == Raw,则 \\'batch\\',\\'date_fabrication\\',\\'product_sell_id\\' 和 \\'buyer_id\\' == null,其余的得到 $faker-> 无论它们是什么类型.
您可以从返回的数组中生成一些数据,并有条件地设置其他字段。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php use Faker\\Generator as Faker; $factory->define(App\\ItemDoEstoque::class, function (Faker $faker) { $orgiem = $faker->randomElement(['Fabrication','Raw','Resale','Cleaning','Others']); return [ 'origem' => $orgiem , 'quantity' => rand(100,999), 'batch' => $orgiem == 'Fabrication' ? null : $faker->ean13, ... ]; }); |