一、hasMany 模型
- hasMany 模式,适合主表关联附表,实现一对多查询
//hasMany('关联模型',['外键','主键']);
return $this->hasMany(Profile::class,'user_id','id');
- 案例
//关联查询
$user = UserModel::find(19);
return json($user->profile);
//数据筛选查询
$user->profile->where('id','>=',10);//键值不一样
$user->profile()->where('id','>=',10)->select();
//has() 方法,查询关联附表的主表内容,比如大于2条的主表记录
UserModel::has('profile','>=',2)->select();
//
UserModel::hasWhele('profile',['status'=>1])->select();
//save() 和 saveAll() 关联新增和批量新增
$user->profile()->save(['hobby'=>'学习','status'=>1]);
$user->profile()->saveAll([
['hobby'=>'PHP','status'=>1],
['hobby'=>'JAVA','status'=>1]
]);
//together()方法,可以删除主表内容时,将附表关联的内容也全部删除
$user = UserModel::with('profile')->find(22);
$user->together(['profile'])->delete();
版权声明:本文为xueerkeji原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。