Laravel 5.1工厂定义无法解决外来关系的关闭问题

时间:2018-03-29 15:04:42

标签: php laravel laravel-5 phpunit factory

我无法定义工厂功能来处理我的业务模型的外部关系。这是我的商业模型工厂的代码。我得到的错误信息是:

  

未捕获的异常'ErrorException',消息为'Object of class   Closure无法转换为字符串'in   /Users/patricia/​​Code/thank-views/vendor/laravel/framework/src/Illuminate/Database/Connection.php:390   堆栈跟踪

似乎无法解析用户的ID。当我在修补程序中运行它时,它会为这些字段创建一个带闭包函数的模型。但是我希望能够生成这些模型以用于我的BusinessTest类。它无法解决这些依赖关系。我不确定解决这些依赖关系的最佳位置是在ModelFactory还是在代码库的其他地方。

$factory->define(App\Business::class, function (Faker\Generator $faker) {
return [
    'slug' => $faker->word,
    'name' => $faker->name,
    'end_card' => $faker->word,
    'white_label' => $faker->boolean,
    'white_label_url' => $faker->word,
    'payment_header' => $faker->word,
    'payment_amount' => $faker->randomNumber(),
    'payment_amount_display' => $faker->word,
    'payment_cost' => $faker->randomNumber(),
    'payment_activated' => $faker->boolean,
    'main_user_id' => function () {
         return factory(App\User::class)->create()->id;
    },
];});

1 个答案:

答案 0 :(得分:0)

你可以改为:

 'main_user_id' => $factory->create(\App\User::class)->id

或:

'main_user_id' => $faker->unique()->numberBetween($min = 1, $max = 50)

或:

 'main_user_id' => $faker->unique()->randomDigit