如果模型事实如下,那么如何在其中使用Trait getData()?
此代码无效。
<?php
use App\Working;
use App\Traits\Calculate;
...
$factory->define(App\Working::class, function (Faker\Generator $faker) {
...
$getData = $this->getData();
...
return['get_data' => $getData];
}
错误消息:
Symfony \ Component \ Debug \ Exception \ FatalThrowableError:调用未定义的方法Illuminate \ Database \ Eloquent \ Factory :: getData()
异常跟踪:
1 Illuminate \ Database \ Eloquent \ Factory :: {closure}(Object(Faker \ Generator),[]) G:\ test \ vendor \ laravel \ framework \ src \ Illuminate \ Database \ Eloquent \ FactoryBuilder.php:263
2 call_user_func(Object(Closure),Object(Faker \ Generator),[]) G:\ test \ vendor \ laravel \ framework \ src \ Illuminate \ Database \ Eloquent \ FactoryBuilder.php:263
答案 0 :(得分:5)
可能不是您要找的东西,但这里有:
您可以创建一个内联类,该类定义一个函数,该函数返回要使用的实际函数。该内联类可以使用特征。
注意:PHP 7中添加了匿名类
<?php
use App\Working;
use App\Traits\Calculate;
// ...
$factory->define(App\Working::class, (new class {
use Calculate;
public function generatorFunction() {
return function (Faker\Generator $faker) {
// ...
$getData = $this->getData();
// ...
return ['get_data' => $getData];
};
}
})->generatorFunction());