gpt4 book ai didi

php - Laravel 工厂和播种 : Static array of arrays

转载 作者:行者123 更新时间:2023-12-04 01:43:58 24 4
gpt4 key购买 nike

对于我的某些表,我想插入固定数量的包含特定数据的行。

这是我的类别工厂:

$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
有没有办法使用种子和工厂将固定数量的静态信息插入某些表中?

最佳答案

我认为您想将 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它将完成。

关于php - Laravel 工厂和播种 : Static array of arrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56100329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com