[TOC]
# 例子1
我們定義兩個模型:Article 和 Tag,分別表示文章和標簽,他們是多對多的關系。表結構應該是這樣的:
~~~
article: id ... ...
tag: id ... ...
article_tag: article_id tag_id
~~~
在 Model 中使用:
2邊都是 ` belongsToMany`
~~~
class Tag extends Eloquent {
protected $table = 'tags';
public function belongsToManyArticle()
{
return $this->belongsToMany(Article::class, 'article_tag', 'tag_id', 'article_id');
}
}
~~~
需要注意的是,第三個參數是本類的 id,第四個參數是第一個參數那個類的 id。
使用跟 hasMany 一樣:
~~~
$tagsWithArticles = Tag::find(1)->belongsToManyArticle()->get();
~~~
在這里給大家展示一個少見用法(奇技淫巧):
~~~
public function parent_video()
{
return $this->belongsToMany($this, 'video_hierarchy', 'video_id', 'video_parent_id');
}
public function children_video()
{
return $this->belongsToMany($this, 'video_hierarchy', 'video_parent_id', 'video_id');
}
~~~
對,你沒有看錯,可以 belongsToMany 自己。
## 總結
**查詢**
~~~
$tObj = $tag->find(1);
$res = $tObj->belongsToManyArticle()->get()->toArray();
dd($res);
~~~
**加入中間表的字段**
~~~
$aObj = $article->find(1);
//zname是中間表字段,根據中間表過濾
$res = $aObj->belongsToManyTag()->wherePivotIn('zname', ['at1', 'at2', 'at9', 'at10'])->get()->toArray();
//返回值是tag表數據加上pivot
dd($res);
~~~
**with把2邊都查出來**
~~~
//確定a的記錄
$aObj = $article->find(1);
//以Article為開始,方法名為鍵進行把Article和tag取出來
$res = $aObj->with('belongsToManyTag')->get()->toArray();
dd($res);
~~~
**with查詢使用查詢條件**
~~~
//一開始指定Article的id是不行的
$res = $article->with([
'belongsToManyTag' => function ($query) {
//是以tag表為查詢條件
$query->where('tname', 't8');
},
])->find(1)->toArray(); //只有在后面指定Article的id才有用
//以Article為開始,方法名為鍵進行把Article和tag取出來
dd($res);
~~~
**新增**
**會重復新增**
~~~
//確定a的記錄
$aObj = $article->find(1);
//新增個tag的記錄
$tag->tname = 't7';
//把Article和新增的tag記錄關聯起來,第二個參數是中間表數據
$res = $aObj->belongsToManyTag()->save($tag, ['zname' => '新增個記錄']);
//返回值是tag新增的對象
dd($res);
~~~
**刪除**
~~~
//確定a的記錄
$aObj = $article->find(1);
//會把和Article關聯的tag全部刪除,但是中間表不動,不建議使用
$res = $aObj->belongsToManyTag()->delete();
//返回值是修改的個數
dd($res);
~~~
**attach新增關聯**
**會重復添加的,添加前先看下**
~~~
$aObj = $article->find(5);
//把5這個$article的id,關聯到$tag的3上
$tObj = $tag->find(3);
$tid= $tObj->getKey(); //這返回的就是個int 主鍵,為了演示getKey方法
//沒有返回值,會重復添加的
$aObj->belongsToManyTag()->attach($tid);
~~~
**detach解除關聯**
~~~
$aObj = $article->find(5);
//把5這個$article的id,關聯到$tag的3上
$tObj = $tag->find(3);
$tid= $tObj->getKey(); //這返回的就是個int 主鍵,為了演示getKey方法
//解除關聯
$res = $aObj->belongsToManyTag()->detach([$tid, 1]);
//仿佛解除關聯的個數
dd($res);
~~~
**sync同步,只管中間表**
第二個參數true還是false表示要不要移除現有的不在你里面的key
false表示不移除
~~~
$aObj = $article->find(1);
//sync是別人的id,他只管中間表,別人有沒有,他不管
$res = $aObj->belongsToManyTag()->sync([4, 6, 3, 5], true);
//返回值告訴你關聯了哪些別人的id,解除了哪些別人的id
dd($res);
~~~
如果您不想移除現有的 IDs,可以使用`syncWithoutDetaching`方法:
~~~php
$user->roles()->syncWithoutDetaching([1, 2, 3]);
~~~
**修改中間表字段的值**
~~~
$aObj = $article->find(1);
//zname是中間表字段,把2個關聯的中間表字段修改
$res = $aObj->belongsToManyTag()->updateExistingPivot(4, ['zname' => '修改的name']);
//返回值是修改的個數
dd($res);
~~~
**切換關聯**
多對多關聯也提供了一個`toggle`方法用于「切換」給定 IDs 的附加狀態。如果給定 ID 已附加,就會被移除。同樣的,如果給定 ID 已移除,就會被附加:
~~~php
$user->roles()->toggle([1, 2, 3]);
~~~
# 例子2
用戶可以擁有多個用戶組 roles 用戶組表
| 鍵名 | 類型 |
| --- | --- |
| id | PK |
| name | varchar(150) |
| display_name | varchar(250) |
| created_at | timestamp |
| updated_at | timestamp |
role_user 用戶組-用戶關聯表
| 鍵名 | 類型 |
| --- | --- |
| id | PK |
| user_id | FK users's id,user_id,role_id 聯合去重 |
| role_id | FK roles's id |
| created_at | timestamp |
| updated_at | timestamp |
## 實現
User.php
~~~
function roles() {
//參數順序為model, table, foreign_key, other_key
return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');
}
~~~
> ID 參數的順序可以這么記:
>
> foreign_key 為CLASS的 id 的外鍵 對應 users' id
> other_key 為FUNCTION的 id 的外鍵 對應 roles' id
Role.php
~~~
function users() {
//外鍵參數順序與上面相反
return $this->belongsToMany(User::class, 'role_user', 'role_id', 'user_id');
}
~~~
> role_user 是關聯表,單詞為單數,并且無需創建Model
## 操作
~~~
$user = User::find(1);
$role = Role::where('name', 'vip1')->first();
~~~
### 查
~~~
//同 一對多 一樣
foreach($user->roles as $role)
echo $role->display_name;
~~~
### 新增,修改,刪除
#### attach 新增關聯
~~~
//給用戶添加vip1的用戶組
$user->roles()->attach($role->getKey()); //$role->getKey() 是個數字
//或
$user->roles()->attach($role);
//上面這個在tinker模擬成功了,好像返回null不知為何,而且有了關聯還能添加
~~~
#### detach 解除關聯
~~~
//解除用戶vip1的用戶組
$user->roles()->detach($role->getKey());
//或
$user->roles()->detach($role);
//解除數組
$user->roles()->detach([$roleID1, $roleID2);
//解除所有
$user->roles()->detach();
//這個在tinker模擬成功了,會有返回值,奇怪了,沒有的話刪除是返回0,有的話返回刪除的記錄條數
~~~
#### sync 同步(可同時新增/刪除)
在上例中,attach方法并不會檢查關聯的重復項,如果重復的attach同一項,案例中數據庫會報插入重復鍵而報錯。此時,就需要使用sync。
> 針對可以插入多條的業務(比如重復投票),可以一直attach
#### - sync([], true);
假設 用戶原用戶組為[1, 3],需要修改關聯的用戶組為1, 3, 4
~~~
$user->roles()->sync([1, 3, 4], true);
//第二個參數為true,相當于(但不等同于):
$user->roles()->detach();
$user->roles()->attach(1);
$user->roles()->attach(3);
$user->roles()->attach(4);
~~~
> 為什么不等同于detach()呢,因為sync方法,并不會將之前的[1, 3]解除關聯(不會delete)。所以可以保留role_user中的[1, 3]的數據,對于某些需要保留數據的場景,此點很有用(比如該數據中還有額外的字段)。
>但是有個問題是比如sync([1, 3, 4], true);他要新增1,3,4關聯到用戶這,但是用戶組那沒有4這個id,他不檢查的,只管中間表
>
> 額外字段,參見下文的 withPivot withTimestamps
#### - sync([], false);
#### - syncWithoutDetaching([]);
~~~
假設用戶原用戶組為[1, 3, 4],現在需要添加[5,7]到用戶組,也就是最終結果為[1, 3, 4, 5, 7]
$user->roles()->sync([5,7], false);
$user->roles()->syncWithoutDetaching([5, 7]);
//即使此時插入重復項也可,比如:
$user->roles()->sync([1,3,5,7], false);
~~~
### 關聯表中有其他數據(額外字段)
#### 時間 withTimestamps
在「示例表」role_user 中,有 created_at updated_at 時間字段,表示用戶組什么時候被添加,什么時候被修改
User.php
//加上withTimestamps 系統會自動維護這兩個字段
~~~
function roles() {
return $this->belongsToMany('App\\Role', 'role_user', 'user_id', 'role_id')->withTimestamps();
}
~~~
讀取
~~~
foreach ($user->roles as $role) {
echo $role->pivot->created_at;
}
~~~
#### pivot 其他數據
role_user 用戶組-用戶關聯表
| 鍵名 | 類型 |
| --- | --- |
| id | PK |
| user_id | user_id,role_id 聯合去重 |
| role_id | FK roles's id |
| column1 | varchar(100) |
| column2 | varchar(200) |
User.php
~~~
function roles() {
return $this->belongsToMany('App\\Role', 'role_user', 'user_id', 'role_id')->withPivot('column1', 'column2');
}
~~~
如果沒有withPivot,返回的pivot中只會有user_id,role_id
#### 讀取
~~~
foreach ($user->roles as $role) {
echo $role->pivot->column1;
}
~~~
#### 寫入
~~~
$user->roles()->attach(3, ['column1' => 'XX', 'column2' => 'YY']);
$user->roles()->attach([1 => ['column1' => 'XX'], 2, 3]);
$user->roles()->sync([1 => ['column1' => 'XX'], 2, 3]);
$user->roles()->save($role, ['column1' => 'XX']);
~~~
#### 修改
`$user->roles()->updateExistingPivot($roleId, ['column1' => 'XX']);`
使用updateExistingPivot方法更新中間表
~~~
$user = App\User::find(1);
$user->roles()->updateExistingPivot($roleId, $attributes);
~~~
#### 查詢
~~~
$user->roles()->wherePivot('column1', 'XX');
$user->roles()->wherePivotIn('column1', ['XX', 'YY']);
...
//或在設置關系時
function special_roles() {
return $this->belongsToMany('App\\Role'...)->wherePivot(...);
}
~~~
中間表查詢條件
當查詢時需要對使用中間表作為查詢條件時,可以使用`wherePivot, wherePivotIn,orWherePivot,orWherePivotIn`添加查詢條件。
~~~
$enterprise->with(['favorites' => function($query) {
$query->wherePivot('enterprise_id', '=', 12)->select('id');
}]);
~~~
- 配置
- composer安裝
- composer用法
- composer版本約束表達
- phpstorm
- sftp文件同步
- php類型約束
- laradock
- 配置文件緩存詳解
- git
- 自定義函數
- 核心概念
- IOC
- 服務提供者
- Facade
- 契約
- 生命周期
- 路由
- 請求
- 命名路由
- 路由分組
- 資源路由
- 控制器路由
- 響應宏
- 響應
- Command
- 創建命令
- 定時任務
- console路由
- 執行用戶自定義的定時任務
- artisan命令
- 中間件
- 創建中間件
- 使用中間件
- 前置和后置
- 詳細介紹
- 訪問次數限制
- 為 VerifyCsrfToken 添加過濾條件
- 單點登錄
- 事件
- 創建
- ORM
- 簡介
- DB類
- 配置
- CURD
- queryScope和setAttribute
- 查看sql執行過程
- 關聯關系
- 一對一
- 一對多
- 多對多
- 遠程關聯
- 多態一對多
- 多態多對多
- 關聯數據庫的調用
- withDefault
- 跨模型更新時間戳
- withCount,withSum ,withAvg, withMax,withMin
- SQL常見操作
- 模型事件
- 模型事件詳解
- 模型事件與 Observer
- deleted 事件未被觸發
- model validation
- ORM/代碼片段
- Repository模式
- 多重where語句
- 中間表類型轉換
- Collection集合
- 新增的一些方法
- 常見用法
- 求和例子
- 機場登機例子
- 計算github活躍度
- 轉化評論格式
- 計算營業額
- 創建lookup數組
- 重新組織出表和字段關系并且字段排序
- 重構循環
- 其他例子
- 其他問題一
- 去重
- 第二個數組按第一個數組的鍵值排序
- 搜索ES
- 安裝
- 表單
- Request
- sessiom
- Response
- Input
- 表單驗證
- 簡介
- Validator
- Request類
- 接口中的表單驗證
- Lumen 中自定義表單驗證返回消息
- redis
- 廣播事件
- 發布訂閱
- 隊列
- 守護進程
- redis隊列的坑
- beanstalkd
- rabbitmq
- redis隊列
- 日志模塊
- 錯誤
- 日志詳解
- 數據填充與遷移
- 生成數據
- 數據填充seed
- migrate
- 常見錯誤
- Blade模板
- 流程控制
- 子視圖
- URL
- 代碼片段
- Carbon時間類
- 一些用法
- 郵件
- 分頁
- 加密解密
- 緩存
- 文件上傳
- 優化
- 隨記
- 嵌套評論
- 判斷字符串是否是合法的 json 字符串
- 單元測試
- 計算出兩個日期的diff
- 自定義一個類文件讓composer加載
- 時間加減
- 對象數組互轉方法
- 用戶停留過久自動退出登錄
- optional 輔助方法
- 文件下載
- Api
- Dingo api
- auth.basic
- api_token
- Jwt-Auth
- passport
- Auth
- Authentication 和 Authorization
- Auth Facade
- 授權策略
- Gates
- composer包
- debug包
- idehelp包
- image處理
- 驗證碼
- jq插件
- 第三方登錄
- 第三方支付
- log顯示包
- 微信包
- xss過濾
- Excel包
- MongoDB
- php操作
- 聚合查詢
- 發送帶附件郵件
- 中文轉拼音包
- clockwork網頁調試
- emoji表情
- symfony組件
- swooletw/laravel-swoole
- 常見問題
- 跨域問題
- Laravel隊列優先級的一個坑
- cache:clear清除緩存問題
- .env無法讀取
- 源碼相關基礎知識
- __set和__get
- 依賴注入、控制反轉和依賴倒置原則
- 控制反轉容器(Ioc Container)
- 深入服務容器
- call_user_func
- compact
- 中間件簡易實現
- array_reduce
- 中間件實現代碼
- Pipeline管道操作
- composer自動加載
- redis延時隊列
- 了解laravel redis隊列
- cli
- 源碼解讀
- Facade分析
- Facade源碼分析
- IOC服務容器
- 中間件原理
- 依賴注入淺析
- 微信
- 微信公眾號
- 常用接收消息
- 6大接收接口
- 常用被動回復消息
- 接口調用憑證
- 自定義菜單
- 新增素材
- 客服消息
- 二維碼
- 微信語音
- LBS定位
- 網頁授權
- JSSDK
- easywechat
- 小程序
- 小程序配置app.json