多對(duì)多關(guān)聯(lián)
| 版本 | 功能調(diào)整 |
|---|---|
| 5.0.8 | 中間表名無(wú)需前綴,并支持定義中間表模型 |
| 5.0.6 |
attach方法返回值改為Pivot對(duì)象 |
關(guān)聯(lián)定義
例如,我們的用戶(hù)和角色就是一種多對(duì)多的關(guān)系,我們?cè)赨ser模型定義如下:
<?php
namespace appindexmodel;
use thinkModel;
class User extends Model
{
public function roles()
{
return $this->belongsToMany('Role');
}
}
belongsToMany方法的參數(shù)如下:
belongsToMany('關(guān)聯(lián)模型名','中間表名','外鍵名','當(dāng)前模型關(guān)聯(lián)鍵名',['模型別名定義']);
5.0.8+版本開(kāi)始,中間表名無(wú)需添加表前綴,并支持定義中間表模型,例如:
public function roles()
{
return $this->belongsToMany('Role','ppindexmodelAccess');
}
關(guān)聯(lián)查詢(xún)
我們可以通過(guò)下面的方式獲取關(guān)聯(lián)數(shù)據(jù)
$user = User::get(1);
// 獲取用戶(hù)的所有角色
dump($user->roles);
如果要獲取中間表數(shù)據(jù),可以使用
$user = User::get(1);
$roles = $user->roles;
foreach($roles as $role){
// 獲取中間表數(shù)據(jù)
dump($role->pivot);
}
關(guān)聯(lián)新增
$user = User::get(1);
// 增加關(guān)聯(lián)數(shù)據(jù) 會(huì)自動(dòng)寫(xiě)入中間表數(shù)據(jù)
$user->roles()->save(['name'=>'管理員']);
// 批量增加關(guān)聯(lián)數(shù)據(jù)
$user->roles()->saveAll([
['name'=>'管理員'],
['name'=>'操作員'],
]);
只新增中間表數(shù)據(jù),可以使用
$user = User::get(1);
// 僅增加關(guān)聯(lián)的中間表數(shù)據(jù)
$user->roles()->save(1);
// 或者
$role = Role::get(1);
$user->roles()->save($role);
// 批量增加關(guān)聯(lián)數(shù)據(jù)
$user->roles()->saveAll([1,2,3]);
單獨(dú)更新中間表數(shù)據(jù),可以使用:
$user = User::get(1);
// 增加關(guān)聯(lián)的中間表數(shù)據(jù)
$user->roles()->attach(1);
// 傳入中間表的額外屬性
$user->roles()->attach(1,['remark'=>'test']);
// 刪除中間表數(shù)據(jù)
$user->roles()->detach([1,2,3]);
V5.0.6+版本開(kāi)始,attach方法的返回值是一個(gè)Pivot對(duì)象實(shí)例,如果是附加多個(gè)關(guān)聯(lián)數(shù)據(jù),則返回Pivot對(duì)象實(shí)例的數(shù)組。
定義相對(duì)的關(guān)聯(lián)
我們可以在Role模型中定義一個(gè)相對(duì)的關(guān)聯(lián)關(guān)系,例如:
<?php
namespace appindexmodel;
use thinkModel;
class Role extends Model
{
public function users()
{
return $this->belongsToMany('User');
}
}
文檔最后更新時(shí)間:2018-06-09 15:41:20
未解決你的問(wèn)題?請(qǐng)到「問(wèn)答社區(qū)」反饋你遇到的問(wèn)題
