运行 Laravel 5 以编程方式而不是从 CLI 播种
Run Laravel 5 seeder programmatically instead of from CLI
有没有办法从 PHP 而不是从命令行 运行 Laravel 5 播种机。我使用的主机不允许我使用命令行。只是为了确认我想做同样的事情,但在我的应用程序代码中:
php artisan db:seed
您可以使用以下方法:
Artisan::call('db:seed');
要获取最后一个运行命令的输出,您可以使用:
Artisan::output();
如果需要,您也可以直接调用播种器class。
如果您手动创建播种机,请确保您执行了 composer dump-autoload。
那里的代码非常简单:
$seeder = new YourSeederClass();
$seeder->run();
您可以在 运行
上向播种器添加参数
例子
$newSchool = School::create($data);
$schoolMeals = new \MealSeeder();
$schoolMeals->run($newSchool->id);
//校餐
public function run($school = 1)
{
$time = Carbon::now();
App\Meal::create([
'school_id' => $school,
'name' => 'Breakfast',
'slug' => 'breakfast',
'description' => 'Test Meal',
'start_time' => $time->toTimeString(),
'end_time' => $time->addMinutes(60)->toTimeString(),
]);
App\Meal::create([
'school_id' => $school,
'name' => 'Lunch',
'slug' => 'lunch',
'description' => 'Test Meal',
'start_time' => $time->toTimeString(),
'end_time' => $time->addMinutes(60)->toTimeString(),
]);
App\Meal::create([
'school_id' => $school,
'name' => 'Supper',
'slug' => 'supper',
'description' => 'Test Meal',
'start_time' => $time->toTimeString(),
'end_time' => $time->addMinutes(60)->toTimeString(),
]);
}
有没有办法从 PHP 而不是从命令行 运行 Laravel 5 播种机。我使用的主机不允许我使用命令行。只是为了确认我想做同样的事情,但在我的应用程序代码中:
php artisan db:seed
您可以使用以下方法:
Artisan::call('db:seed');
要获取最后一个运行命令的输出,您可以使用:
Artisan::output();
如果需要,您也可以直接调用播种器class。 如果您手动创建播种机,请确保您执行了 composer dump-autoload。
那里的代码非常简单:
$seeder = new YourSeederClass();
$seeder->run();
您可以在 运行
上向播种器添加参数例子
$newSchool = School::create($data);
$schoolMeals = new \MealSeeder();
$schoolMeals->run($newSchool->id);
//校餐
public function run($school = 1)
{
$time = Carbon::now();
App\Meal::create([
'school_id' => $school,
'name' => 'Breakfast',
'slug' => 'breakfast',
'description' => 'Test Meal',
'start_time' => $time->toTimeString(),
'end_time' => $time->addMinutes(60)->toTimeString(),
]);
App\Meal::create([
'school_id' => $school,
'name' => 'Lunch',
'slug' => 'lunch',
'description' => 'Test Meal',
'start_time' => $time->toTimeString(),
'end_time' => $time->addMinutes(60)->toTimeString(),
]);
App\Meal::create([
'school_id' => $school,
'name' => 'Supper',
'slug' => 'supper',
'description' => 'Test Meal',
'start_time' => $time->toTimeString(),
'end_time' => $time->addMinutes(60)->toTimeString(),
]);
}