对于某些表,我想插入固定数量的包含特定数据的行。
这是我的类别工厂:
$factory->define(Category::class, function (Faker $faker) {
return [
[
'name' => 'Politics',
'slug' => 'politics',
'description' => 'To discuss politics'
],
[
'name' => 'News and Events',
'slug' => 'news',
'description' => 'To discuss news and world events'
],
[
'name' => 'Food and Cooking',
'slug' => 'cooking',
'description' => 'To discuss cooking and food'
],
[
'name' => "Animals and Nature",
'slug' => 'animals-nature',
'description' => 'To discuss politics'
]
];
});
这是播种机:
public function run() {
factory(App\Category::class, 1)->create();
}
我收到此错误:preg_match() expects parameter 2 to be string, array given
是否可以使用种子和工厂将固定数量的静态信息插入某些表?
答案 0 :(得分:1)
我认为您想使用带有静态值的Seeder,如果我正确的话,您应该使用
定义类别播种器
<?php
use Illuminate\Database\Seeder;
use App\Category;
class CategorySeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$categories = [
[
'name' => 'Politics',
'slug' => 'politics',
'description' => 'To discuss politics'
],
[
'name' => 'News and Events',
'slug' => 'news',
'description' => 'To discuss news and world events'
],
[
'name' => 'Food and Cooking',
'slug' => 'cooking',
'description' => 'To discuss cooking and food'
],
[
'name' => "Animals and Nature",
'slug' => 'animals-nature',
'description' => 'To discuss politics'
]
];
foreach ($categories as $category) {
Category::create($category);
}
}
}
在DatabaseSeeder中
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
$this->call(CategorySeeder::class);
}
}
现在运行php artisan db:seed
,它将完成。
答案 1 :(得分:0)
@Prafulla Kumar Sahu 的答案是播种机,但您可以通过以下方式 override your factory 值:
$category = factory(App\Category::class)->make([
'name' => 'Politics',
'slug' => 'politics',
'description' => 'To discuss politics'
]);
$category = factory(App\Category::class)->make([
'name' => 'News and Events',
'slug' => 'news',
'description' => 'To discuss news and world events'
]);
$category = factory(App\Category::class)->make([
'name' => 'Food and Cooking',
'slug' => 'cooking',
'description' => 'To discuss cooking and food'
]);
$category = factory(App\Category::class)->make([
'name' => "Animals and Nature",
'slug' => 'animals-nature',
'description' => 'To discuss politics'
]);