Laravel 如果工厂条件不好
我创建了一个工厂文件,以便创建假元素来测试我的web系统。我想知道是否有一种方法可以根据先前创建的元素的值创建另一个元素的if条件 它对简单的模型非常有效,但是对于那些需要元素之间的关系的模型,我找不到一种方法来实现它Laravel 如果工厂条件不好,laravel,factory,Laravel,Factory,我创建了一个工厂文件,以便创建假元素来测试我的web系统。我想知道是否有一种方法可以根据先前创建的元素的值创建另一个元素的if条件 它对简单的模型非常有效,但是对于那些需要元素之间的关系的模型,我找不到一种方法来实现它 <?php use Faker\Generator as Faker; $factory->define(App\ItemDoEstoque::class, function (Faker $faker) { return [ 'orige
<?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=制造,则:
'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\u farcuring'、'product\u sell\u id'和'buyer\u id'==null,其余的得到$faker->不管它们是什么类型。您可以从返回的数组中生成一些数据,并有条件地设置其他字段
<?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,
...
];
});
您可以从返回的数组中生成一些数据,并有条件地设置另一个字段
<?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,
...
];
});