Featured image of post Day 17. Eloquent Relationships 多對多

Day 17. Eloquent Relationships 多對多

資源

Laravel7 30天: 目錄
專案連結: github - laravel7 之 30 天分享

前言

上一篇: Day 16. Eloquent Relationships 一對多
今天要來分享 多對多

關聯表文章區

關聯名稱傳送門
One To One一對一Day 15. Eloquent Relationships 一對一
One To Many多對多Day 16. Eloquent Relationships 一對多
Many To Many多對多Day 17. Eloquent Relationships 多對多
Polymorphic One To One多態的一對一Day 18. Eloquent Polymorphic Relationships 多態的一對一
Polymorphic One To Many多態的一對多Day 19. Eloquent Polymorphic Relationships 多態的一對多
Polymorphic Many To Many多態的多對多Day 20. Eloquent Polymorphic Relationships 多態的多對多

Many To many (多對多)

文件

表的關係

資料表關係如下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
users
    id - integer
    name - string
 
roles
    id - integer
    name - string
 
role_user
    user_id - integer
    role_id - integer

Model 設定

app/Models/User.php

1
2
3
4
5
6
7
class User extends Model
{
    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
}

app/Models/Role.php

1
2
3
4
5
6
7
class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class);
    }
}

如何使用

  • 取得
1
2
3
// 會員取得角色
$user = User::find(1);
$roles = $user->roles;
  • 新增 / 修改 / 刪除
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$user = App\User::find(1);
$rolesId = [1, 2, 3];

# 新增 attach
$user->roles()->attach($rolesId);

# 刪除 detach
$user->roles()->detach($rolesId);

# sync 自動新增、刪除
$user->roles()->sync($rolesId);

snyc 會自動判斷 要新增還是刪除,滿方便的

進階

中間表加入時間戳

預設的中間表只有 兩個有關係表的ID,時間戳要自己加
加也很容易,就是關聯的時候加上 withTimestamps() 就可以

1
2
return $this->belongsToMany(Role::class)
                ->withTimestamps();

自定義使用中間表

我們預設使用中間表都是使用 pivot
使用方式如下

1
2
3
4
5
$user = User::find(1);
 
foreach ($user->roles as $role) {
    echo $role->pivot->created_at;
}

所以如果要字定義的話可以再關聯的時候使用 as 參考一下範例

1
2
3
return $this->belongsToMany(Role::class)
                ->as('rrr')
                ->withTimestamps();

使用的時候就會變成 …

1
2
3
foreach ($user->roles as $role) {
    echo $role->rrr->created_at;
}

自訂中間表

中間表(pivot) 官方會有預設的表名,
就是兩個關係表的表名,字母在前面的是前面

1
2
users - role_user - roles
aaa - aaa_bbb - bbb

但其實有時候會不是妳要的名稱
所以我們可以建 pivot 會員以及角色中間表 role_user 預設就是 RoleUser
如果妳希望是 UserRole 的話 …

1
php artisan make:model UserRole -p

關聯的時候使用 using() 就可以了

1
2
3
4
return $this->belongsToMany(Role::class)
                ->using(UserRole::class)  
                ->as('rrr')
                ->withTimestamps();

結語

當初我要理解多對多也卡很久
後來也是參考 Laravel Daily 的影片才會使用

附上連結: Laravel Daily Pivot Table

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy