如果条件在工厂Laravel

时间:2019-04-11 16:45:43

标签: laravel factory

我创建了一个工厂文件,以便创建假元素来测试我的Web系统。而且我想知道是否有一种方法可以根据先前创建的元素的值来创建另一个元素的if条件。

它与简单的模型完美搭配,但是对于那些需要在元素之间建立关系的模型,我找不到解决方法。

import Basic from './basic'
...
const NewModal = newModal(Basic, data)
...
render()
<NewModal ... />

我期望的是: 如果origem = Fabrication,则批次,product_sell_id,数量和date_fabrication不会为空,但其余部分必须为空。 如果origem = Raw,则:

<?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' => 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'== Raw,则'batch','date_fabrication','product_sell_id'和'buyer_id'== null,其余的则取$ faker->不管它们是什么类型。

1 个答案:

答案 0 :(得分:0)

您可以从返回的数组中生成一些数据,并有条件地设置其他字段。

<?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,
        ...            
    ];
});