Laravel 将变量从一个种子文件传递到另一个?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32342289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel passing variables from one seed file to another?
提问by Sosa
I have created multiple seed files and my main DatabaseSeeder file looks like this:
我创建了多个种子文件,我的主要 DatabaseSeeder 文件如下所示:
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$name1 = "James";
$name2 = "Jeff";
$name3 = "Joe";
$this->call(UserTableSeeder::class);
$this->call(PersonTableSeeder::class);
$this->call(IndividualTableSeeder::class);
$this->call(HumanTableSeeder::class);
}
}
How can I make it so that UserTableSeeder and PersonTableSeeder gets the variables from my main seeder file? (What I'm really trying to do is use Faker to output random values, but use the same value for each table seeder)
我怎样才能让 UserTableSeeder 和 PersonTableSeeder 从我的主种子文件中获取变量?(我真正想做的是使用 Faker 输出随机值,但对每个表播种机使用相同的值)
回答by Or Bachar
I had the same problem, ended up overriding the call() function by adding $extra var and passing it to run() function.
我遇到了同样的问题,最终通过添加 $extra var 并将其传递给 run() 函数来覆盖 call() 函数。
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$name1 = "James";
$name2 = "Jeff";
$name3 = "Joe";
$this->call(UserTableSeeder::class, $name1);
$this->call(PersonTableSeeder::class);
$this->call(IndividualTableSeeder::class);
$this->call(HumanTableSeeder::class);
}
public function call($class, $extra = null) {
$this->resolve($class)->run($extra);
if (isset($this->command)) {
$this->command->getOutput()->writeln("<info>Seeded:</info> $class");
}
}
}
and then add $extra to your seeder class
然后将 $extra 添加到您的播种机类
// database/seeds/UserTableSeeder.php
/**
* Run the database seeds.
*
* @return void
*/
public function run($extra = null)
{
var_dump($extra);
}
hope it helps.
希望能帮助到你。
回答by chojnicki
Anyone who is also looking for this. Accepted answer will work, but why over complicate such simple things?
任何也在寻找这个的人。接受的答案会起作用,但为什么要把这么简单的事情复杂化呢?
Just use constants or globals.
只需使用常量或全局变量。
DatabaseSeeder.php
数据库浏览器.php
define('SEEDING_SIZE', 10);
Now in any seeder this will be available as "SEEDING_SIZE".
现在在任何播种机中,这将作为“SEEDING_SIZE”提供。
No extra functions needed.
不需要额外的功能。