如何使用 Laravel 种子程序和 Eloquent 模型用样本数据填充数据库

Laravel’s Seeders是Laravel项目中的数据库/seeders目录中生活的特殊类,允许您在数据库中编程地插入默认或样本记录的集合。

在代码编辑器中,打开以下文件:

1database/seeders/LinkSeeder.php

它将包含以下代码:

 1[label database/seeders/LinkSeeder.php]
 2<?php
 3
 4namespace Database\Seeders;
 5
 6use App\Models\Link;
 7use Illuminate\Database\Seeder;
 8use Illuminate\Support\Facades\DB;
 9use Symfony\Component\Yaml\Yaml;
10
11class LinkSeeder extends Seeder
12{
13    /**
14     * Run the database seeds.
15     *
16     * @return void
17     */
18    public function run()
19    {
20        //only import seeds if DB is empty.
21        if (!Link::count()) {
22            $this->importLinks();
23        }
24    }
25
26    /**
27     * Imports Links from the default links.yml file at the root of the app.
28     * Change that file to import a set of personal basic links you want to show
29     * as soon as the application is deployed.
30     */
31    public function importLinks()
32    {
33        $links_import_path = __DIR__ . '/../../links.yml';
34
35        $yaml = new Yaml();
36        if (is_file($links_import_path)) {
37            $links = $yaml->parsefile($links_import_path);
38
39            foreach ($links as $link) {
40                DB::table('links')->insert([
41                    'url' => $link['url'],
42                    'description' => $link['description']
43                ]);
44            }
45        }
46    }
47}

请注意,此代码不使用链接模型,而是使用 查询构建器在数据库中插入新链接,这是Laravel中与数据库记录的不同工作方式,不依赖于Eloquent模型。

要改进此代码,您将更改前方循环以使用 Eloquent 模型,而不是直接通过查询构建程序查询数据库,您还需要在循环开始之前创建一个默认的链接列表(以下代码中称为$default_list),以便您可以在创建的每一个新链接中引用此列表。

用以下代码更换您的播种类中的当前内容:

 1[label database/seeders/LinkSeeder.php]
 2<?php
 3
 4namespace Database\Seeders;
 5
 6use App\Models\Link;
 7use App\Models\LinkList;
 8use Illuminate\Database\Seeder;
 9use Illuminate\Support\Facades\DB;
10use Symfony\Component\Yaml\Yaml;
11
12class LinkSeeder extends Seeder
13{
14    /**
15     * Run the database seeds.
16     *
17     * @return void
18     */
19    public function run()
20    {
21        //only import seeds if DB is empty.
22        if (!Link::count()) {
23            $this->importLinks();
24        }
25    }
26
27    /**
28     * Imports Links from the default links.yml file at the root of the app.
29     * Change that file to import a set of personal basic links you want to show
30     * as soon as the application is deployed.
31     */
32    public function importLinks()
33    {
34        $links_import_path = __DIR__ . '/../../links.yml';
35
36        $yaml = new Yaml();
37        if (is_file($links_import_path)) {
38            $links = $yaml->parsefile($links_import_path);
39
40            $default_list = new LinkList();
41            $default_list->title = "Default";
42            $default_list->description = "Default List";
43            $default_list->slug = "default";
44            $default_list->save();
45
46            foreach ($links as $link) {
47                $seed_link = new Link();
48                $seed_link->url = $link['url'];
49                $seed_link->description = $link['description'];
50
51                $default_list->links()->save($seed_link);
52            }
53        }
54    }
55}

更新的代码使用面向对象的方法来设置由Eloquent转换为表列的LinkListList模型的属性。为循环的最后一行使用$default_listlinks表的引用,可通过links()方法访问,以便在该列表中保存新的链接。

完成后保存文件 Laravel 播种器只在数据库空时运行,以免与以其他方式插入数据库的实际数据发生冲突。

运行以下命令来删除开发数据库:

1docker-compose exec app php artisan db:wipe
1[secondary_label Output]
2Dropped all tables successfully.

现在,要重新创建表 **并运行更新的播种器,您可以使用以下命令手工迁移 - 种子:

1docker-compose exec app php artisan migrate --seed

您应该收到类似于以下的输出:

 1[secondary_label Output]
 2Migration table created successfully.
 3Migrating: 2014_10_12_000000_create_users_table
 4Migrated:  2014_10_12_000000_create_users_table (124.20ms)
 5Migrating: 2014_10_12_100000_create_password_resets_table
 6Migrated:  2014_10_12_100000_create_password_resets_table (121.75ms)
 7Migrating: 2019_08_19_000000_create_failed_jobs_table
 8Migrated:  2019_08_19_000000_create_failed_jobs_table (112.43ms)
 9Migrating: 2020_11_18_165241_create_links_table
10Migrated:  2020_11_18_165241_create_links_table (61.04ms)
11Migrating: 2021_07_09_122027_create_link_lists_table
12Migrated:  2021_07_09_122027_create_link_lists_table (112.18ms)
13Seeding: Database\Seeders\LinkSeeder
14Seeded:  Database\Seeders\LinkSeeder (84.57ms)
15Database seeding completed successfully.

在本系列的下一章中,您将详细了解如何使用 Eloquent 查询数据库记录。

Published At
Categories with 技术
comments powered by Disqus