大家好~
今天要开始实作留言功能,
个人习惯先从建立 Model 开始,
在建立 Model 时,
指令可以带上不同参数,
可以一起生成其他所需档案。
使用 make:model
可以快速创建 Model class。
php artisan make:modle ModelName
带上不同参数可以建立其他相关 class。
以下生成指令节录至 Laravel 官方文件。
# Generate a model and a database migration...
php artisan make:model Flight --migration
php artisan make:model Flight -m
# Generate a model and a FlightFactory class...
php artisan make:model Flight --factory
php artisan make:model Flight -f
# Generate a model and a FlightSeeder class...
php artisan make:model Flight --seed
php artisan make:model Flight -s
# Generate a model and a FlightController class...
php artisan make:model Flight --controller
php artisan make:model Flight -c
# Generate a model and a migration, factory, seeder, and controller...
php artisan make:model Flight -mfsc
# Shortcut to generate a model, migration, factory, seeder, and controller...
php artisan make:model Flight --all
# Generate a pivot model...
php artisan make:model Member --pivot
至於本专案目前预计会用到的只有 Controller 与 Migration,
所以指令的部分我们只要带上 -cm
就可以了~
php artisan make:model Message -cm
成功後会建立以下三个档案:
Migration 内会有两个 function,
分别是 up()
与 down()
;
up()
:执行 php artisan migrate
时会执行的部分。
down()
:执行 php artisan migrate:rollback
时会执行的部分。
public function up()
{
Schema::create('messages', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id');
$table->string('title');
$table->string('content');
$table->timestamps();
});
}
使用 php artisan migrate
执行 migration
php artisan migrate
执行完指令後,
就可以看到我们的资料表已经生成罗。
Laravel 的 Migration 提供许多的 Available Column Types 与 Column Modifiers 可以使用,
使用方式也很简单~
接下来要把 Model 加上关联关系。
一位 User 可以有多则 Messages,
一则 Message 只能属於一位 User 发布的。
来建立 Model 的一对多关联关系吧!
public function messages()
{
return $this->hasMany(Message::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
这样关联关系就建立好了。
Eloquent 会将所属 Model 名称转成 Snake Case 形式,
再加上 _id
後缀作为外键名称。
以上面的关联关系为例,
Eloquent 就会使用 user_id
当作外键名称。
下图是节录至 src/Illuminate/Database/Eloquent/Model.php
中取得外键名称的部分,
有兴趣的可以看看~
使用 create( )
建立资料时,
如果没在 Model 指定 fillable
或 guarded
其中一种属性的话,
我们的 Model 就无法进行批量赋值喔。
protected $fillable=[
'title',
'content'
];
在 app/Models/Message.php
内,
使用 $fillable
允许 title 与 content 可以被批量赋值。
资料库建好了,
关联关系也用好了,
明天就开始来做 CRUD 吧!
大家明天见啦~
若文章有任何问题,
还请大家不吝赐教!
>>: [ Day 04 ] Virtual DOM ? ReactDOM ?
说明 晚点补 程序码 #include <stdbool.h> #include <...
今年的疫情蛮严重的,希望大家都过得安好,希望疫情快点过去,能回到一些线下技术聚会的时光~ 今天要开始...
原理说明 SVM (support vector machine 支援向量机),是在特徵空间中找到一...
CLA以及bit乘法 tags: IT铁人 例题答案 就简单把答案打出来罗~ 小心转换成二位元不要粗...
.任意访问控制(DAC)依赖於所有者(通常基於身份)自行决定是否进行授权。 .基於角色的访问控制(...