关联关系
1 belongsTo使用【一对一关系或一对多,子类使用,关联健在本模型中】
belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null)
1)当order表中外键为user_id user表主键为id时
return $this->belongsTo('Models\User');
2)当order表中外键为user_id user表主键为uid
return $this->belongsTo('Models\User', 'user_id', 'uid');
 
2 hasOne使用 【一对一关系,关联键在子关联表中,父类使用】
hasOne($related, $foreignKey = null, $localKey = null)
1)hasOne('关联模型名','外键名','主键名',['模型别名定义'],'join类型');
$this->hasOne('Image','product_id','id');
 
3 belongsToMany 使用【多对多关系】
belongsToMany($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null,
$parentKey = null, $relatedKey = null, $relation = null)
1)三张表,user 为表1,t2为表2,t3 为表1跟表2的关联表
需求,一个用户表admin里面有role_id字段,org_role_permit(表3)表菜单menu与admin的映射表
return $this->belongsToMany('App\Models\System\Menu'(t2), 'org_role_permit'(t3), 'role_id'(t1.role_id), 'menu_id'(t2.menu_id));
得到的sql
select `system_menu`.*, `org_role_permit`.`role_id` as `pivot_role_id`,
`org_role_permit`.`menu_id` as `pivot_menu_id`
from `system_menu` inner join `org_role_permit`
on `system_menu`.`menu_id` = `org_role_permit`.`menu_id`
where `org_role_permit`.`role_id` = 2
 
4 hasMany 使用【一对多关系 】
hasMany($related, $foreignKey = null, $localKey = null)
1)question (t1) 和 answer (t2) 一个答案只可以对应一个问题
return $this->hasMany(Answer::class, 'question_id'(t2), 'id'(t1.id));
 
 
 
1 laravel关联模型中的多对多关系解析-belongsToMany
员工表-employee employee_id
任务表- task task_id
 
员工与任务的关联表 task_target
task_target_id-自增ID
target_type-参与任务的类型,员工或者门店团队
target_id-参与对象的ID
public function hasManyTask()
{ return $this->belongsToMany(Task::class,'task_target','target_id','task_id','employee_id')
->wherePivot('target_type','=',Target::TARGET_TYPE_EMPLOYEE); }
【注,例子质量不高】
belongsToMany参数解析
参数(Task::class)1:是最终要获取数据的表模型
参数(task_target)2:是与本表与第一个参数表的关联表
参数(target_id)3:此参数是foreignPivotKey,是中间表task_target针对本表的外键
参数(task_id)4:是relatedPivotKey。related 其实是指Task::class表。所以字段其实是中间表task_target针对Task表的外键。
参数(employee_id)5:是parentKey。这个是 where 条件中的字段值
wherePivot 是中间表 task_target 的条件
注:belongsToMany(目标表模型,中间表,本表在中间表中的键名,目标表在中间表中键名)