**一對多hasMany模式**
**1.hasMany模式,適合主表關聯附表,實現一對多查詢,具體設置方式如下:**
**hasMany('關聯模型',\['外鍵','主鍵'\]);**
**return $this->hasMany('profile','user\_id','id');**
**關聯模型(必須):模型名或者模型類名**
**外鍵:關聯模型外鍵,默認的外鍵名規則是當前模型名加\_id**
**主鍵:當前模型主鍵,一般會自動獲取也可以指定傳入**
### ***2.實現的查詢方案:***
**$user = UserModel:get(10);**
**return json($user->profile);**
### ***3.使用->profile()方法模式,可以進一步進行數據的篩選;***
return json($user->profile()->where('id','>',10)->select())
### \*\*\*4.使用has()方法,查詢關聯附表的主表內容,\*\*\*比如大于等于2條的主表記錄,這個也相當于反向查詢了,從附表推出主表數據
UserModel::has('profile','>=',2)->select()
### ***5.使用hasWhere()方法,查詢關聯附表篩選后的記錄***
UserModel::hasWhere('profile',\['status'=>1\])->select();
### ***6.使用save()和saveAll()進行關聯新增和批量關聯新增,方法如下:***
$user = UserModel::get(10);
$user->profile()->save(\['hobby'=>'測試喜好','status'=>1\]);
批量新增
$user->profile()->saveAll(\[
\['hobby'=>'測試喜好','status'=>1\],
\['hobby'=>'測試數據','status'=>1\]
\])
### ***7.使用together()方法,可以刪除主表內容時,將f附表關聯的內容全部刪除***
$user = UserModel::get(221,'profile');
$user->together('profile')->delete()
*****
*****
*****