
最初发表在我的博客,briandouglas.ie
这是有关如何在数据库中添加按省份分组的爱尔兰县的分步指南。
php artisan make:迁移create_provinces_table
我们只需要一个省份的名称。
schema::create('provinces', function (blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
php artisan make:migration create_counties_table
除了名称之外,县还将包含对其所属省份的引用。
schema::create('counties', function (blueprint $table) {
$table->id();
$table->string('name');
$table->foreignidfor(province::class);
$table->timestamps();
});
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);
}
}
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);
}
}
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]);
}
}
}
}
php artisan db:seed --class=provinceseeder
由于省份和县不会改变,所以播种器只需要运行一次。
以上就是在 Laravel 中为爱尔兰县播种数据库的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号