iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 27
0
Modern Web

VUE & PHP (Apache2) & Docker 實戰開發系列 第 27

Day27 - PHP-Laravel Foreign Key 介紹

Laravel也有支援幫資料庫創建foreign key去定義每個table之間的主從關係,
建立彼此的關係前要先動腦好好思考一下才去把code寫好,下面來舉個例子

使用者發表一篇文章這邊就需要兩個table,分別是usersposts

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }
public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }

存檔之後,終端機輸入

php artisan migrate

這裡有個laravel的migration條件就是每個table的先後順序,
一但沒弄好順序是無法建立彼此之間的關係。

這是我剛開始學Laravel時遇到的小問題,
本篇介紹到此,下次見~


上一篇
Day26 - PHP & Docker
下一篇
Day28 - Vue & Container Instance
系列文
VUE & PHP (Apache2) & Docker 實戰開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言