在 Laravel 中为爱尔兰县播种数据库
时间:2024-07-30
浏览:180
作者:佚名
从现在开始,我们要努力学习啦!今天我给大家带来《在 Laravel 中为爱尔兰县播种数据库》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

最初发表在我的博客,briandouglas.ie
这是有关如何在数据库中添加按省份分组的爱尔兰县的分步指南。
第 1 步 - 省份迁移
php artisan make:迁移create_provinces_table
我们只需要一个省份的名称。
schema::create('provinces', function (blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
第 2 步 - 县迁移
php artisan make:migration create_counties_table
除了名称之外,县还将包含对其所属省份的引用。
schema::create('counties', function (blueprint $table) {
$table->id();
$table->string('name');
$table->foreignidfor(province::class);
$table->timestamps();
});
第 3 步 - 省份模型
php artisan make:模型省
这里我们添加 name 作为可填写的属性,并与 county 建立 hasmany 关系。
<?php
namespace app\models;
use illuminate\database\eloquent\factories\hasfactory;
use illuminate\database\eloquent\model;
use illuminate\database\eloquent\relations\hasmany;
class province extends model
{
use hasfactory;
protected $fillable = ['name'];
public function counties(): hasmany
{
return $this->hasmany(county::class);
}
}
第 4 步 - 县模型
php artisan make:模型县
这里我们添加name和province_id作为可填写属性,并与province建立belongsto关系。
<?php
namespace app\models;
use illuminate\database\eloquent\factories\hasfactory;
use illuminate\database\eloquent\model;
use illuminate\database\eloquent\relations\belongsto;
class county extends model
{
use hasfactory;
protected $fillable = ['name', 'province_id'];
public function province(): belongsto
{
return $this->belongsto(province::class);
}
}
第 5 步 - 省份播种者
php artisan make:seeder provinceseeder
provinceseeder 将为爱尔兰每个省创建记录,并附上相关县。
<?php
namespace Database\Seeders;
use App\Models\Province;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class ProvinceSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$irishCounties = [
'Leinster' => [
'Carlow',
'Cavan',
'Dublin',
'Kildare',
'Kilkenny',
'Laois',
'Longford',
'Louth',
'Meath',
'Offaly',
'Westmeath',
'Wexford',
'Wicklow'
],
'Munster' => [
'Clare',
'Cork',
'Kerry',
'Limerick',
'Tippperary',
'Waterford'
],
'Connacht' => [
'Galway',
'Leitrim',
'Mayo',
'Roscommon',
'Sligo'
],
'Ulster' => [
'Antrim',
'Armagh',
'Cavan',
'Derry',
'Donegal',
'Down',
'Fermanagh',
'Monaghan',
'Tyrone'
]
];
foreach ($irishCounties as $provinceName => $countyNames) {
$province = Province::firstOrCreate(['name' => $provinceName]);
foreach ($countyNames as $countyName) {
$province->counties()->firstOrCreate(['name' => $countyName]);
}
}
}
}
第 6 步 - 运行播种机
php artisan db:seed --class=provinceseeder
由于省份和县不会改变,所以播种器只需要运行一次。
今天关于《在 Laravel 中为爱尔兰县播种数据库》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
