Laravel中关联关系总结

33 篇文章 0 订阅

在这里对以下几个函数中的参数做一个总结:

一对一

主键表模型中函数

  • hasOne

参数:

  1. 外键表的模型
  2. 外键表中外键名称
  3. 主键表中外键名称

例:

一个人只有一种DNA,表1 human,外键 human_dna_id,表2dna,主键 dna_id

// human表的模型中
public function AnyFunctionName(){
    return $this->hasOne("App\Dnas\","dna_id","human_dna_id");
}

外键表模型中函数

  • belongsTo

参数:

  1. 主键表模型
  2. 外键表中外键名称
  3. 主键表中外键名称

例:

一个人只有一种DNA,表1 human,外键 human_dna_id,表2dna,主键 dna_id

//dna表模型中
public function AnyFunctionName(){
    return $this->belongsTo("App\Human",'dna_id','human_dna_id');
}

一对多

主键表模型中函数

  • hasMany

参数:

  1. 外键表的模型
  2. 外键表中外键名称
  3. 主键表中外键名称

例:

一个人可以有多部手机,表1,human,外键 telephone_id,表2,phone,主键名称 phone_id

// human表模型中
public function AnyFunctionName(){
    return $this->hasMany("App\Phones","phone_id","telephone_id");
}

外键表模型中函数

  • belongsTo

多对多

主键表模型中函数

  • hasMany

外键表模型中函数

  • belongsToMany

    1. 主键表模型
    2. 关联表名称
    3. 外键表中外键名称
    4. 关联表中主键表名称

例:

实在想不出例子了,就当表1,主键名称为id1,表模型为Table1Model,表2,主键名称为id2,在两者的关联表中字段名称不变,关联表名称为Table1_Table2

// 在外键表的模型中
public function AnyFunctionName(){
    return $this->belongsToMany('Table1Model','Table1_Table2','id2','id1');
}

另外,创建模型的时候记得设置protected $primaryKeyprotected $table,有时候找不到表,找不到字段可能就是这个造成的.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值