iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 21
0
Software Development

後端PHP+Laravel--新手實戰日記系列 第 21

Day21-Laravel新手基礎訓-Eloquent: Relationships-One to One

胎嘎侯~
今天的實戰日記與Eloquent: Relationships有關,簡單來說,Eloquent使管理和使用這些關係變得容易,因為資料庫裡的資料表通常是相互關聯的,多種關係連結使資料表不再獨立封閉。

  • One To One
  • One To Many
  • One To Many (Inverse)
  • Many To Many
  • Defining Custom Intermediate Table Models
  • Has One Through
  • Has Many Through

先來實現每個User都有一個Profile的簡單1對1關係。

One to One

1.首先,建立Eloquent Model Profile,-m是同時產生migration的table。

php artisan make:model Profile -m

2.進入profiles table,在Schema::create增加兩個欄位:

    public function up()
    {
        Schema::create('profiles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('phone');
            $table->unsignedBigInteger('user_id');
            $table->timestamps();
        });
    }

進行資料表生成,輸入php artisan migrate,回到資料庫查看users和profiles這兩個資料表及欄位是否順利生成。

分解Eloquent的1對1關係

  • hasOne:每個User有一個Profile
  • belongsTo:Profile屬於User

3.進入User.php(Model)增加下列方法

    public function profile()
    {
        //每個User都有Profile
        return $this->hasOne('App\Profile'); //綁定與Profile的關係(正向)
    }

4.進入Profile.php(Model)增加下列方法

class Profile extends Model
{
    protected $fillable = [
        'phone','user_id',
    ];
    public function user()
    {
        //Profile屬於User
        return $this->belongsTo('App\User'); //綁定與User的關係(逆向)
    }
}
    }

了解$fillable,同場加映:Mass Assignment

將1對1關係建立完成後,我們要測試關係到底有沒有被綁定,進入api.php增加要測試的路由。

5.建立一個post請求的路由,URI為/user

6.從User(Model)中找第4筆數據,存在$user物件。

7.此時將$user所帶的值連結至profile()中,給profile中的phone新增一個值。

8.firstOrCreate()->如果找不到,就增加;此為判斷profiles table裡的user_id是否為users table的id,若否就新增該筆,並在'phone'欄位新增00000;在未使用firstOrCreate()時,資料庫會接受到同個使用者重複的多筆修改資料,因此這個限制是為了綁定1對1的關係。

Route::post('/user',function (Request $request ){
    
    $user = User::find(4);
    $user->profile()->firstOrCreate(['user_id'=>$user->id],[
        'phone'=>'00000'
    ]);

    dd($user->profile);
});

8.我們利用Postman來查看dd($profile)印出的內容有哪些。

原先user資料表的find(4),成功連結在Profiles中user_id:4,以及phone欄位新增的0000;此外,我們回到資料庫的profile資料表查看。


資料連結成功。

1對1的關係差不多說完了,我們明天見囉!


上一篇
Day20- Laravel新手基礎訓-Eloquent ORM
下一篇
Day22-Laravel新手基礎訓-Eloquent: Relationships-One to Many
系列文
後端PHP+Laravel--新手實戰日記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言