zoukankan      html  css  js  c++  java
  • laravel 关联关系2

    关联关系
    1 belongsTo使用【一对一关系或一对多,子类使用,关联健在本模型中】
    belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null)
    1)当order表中外键为user_id user表主键为id时
    return $this->belongsTo('ModelsUser');
    2)当order表中外键为user_id user表主键为uid
    return $this->belongsTo('ModelsUser', '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('AppModelsSystemMenu'(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(目标表模型,中间表,本表在中间表中的键名,目标表在中间表中键名)

  • 相关阅读:
    http://msdn.microsoft.com/zhcn/library/cc838145(VS.95).aspx
    去除HTML标签2005SQL写法
    UML中符号的意义(转)
    删除DataTable中重复的记录
    Matlab R2010在centost下的安装
    Eclipse 编译 Android工程时,提示该错误 :Error generating final archive: Debug certificate expired on xxxxxx(日期) 解决办法
    centos上安装opencv库
    windows下eclipse远程连接Hadoop集群进行开发
    centos6 上用eclipse调试hadoop程序报org.apache.hadoop.io.compress.SnappyCodec not found错误解决方法
    cocoa设计模式笔记
  • 原文地址:https://www.cnblogs.com/sien6/p/13797109.html
Copyright © 2011-2022 走看看