在这里对以下几个函数中的参数做一个总结:
一对一
主键表模型中函数
- hasOne
参数:
- 外键表的模型
- 外键表中外键名称
- 主键表中外键名称
例:
一个人只有一种DNA,表1 human,外键 human_dna_id,表2dna,主键 dna_id
// human表的模型中
public function AnyFunctionName(){
return $this->hasOne("App\Dnas\","dna_id","human_dna_id");
}
外键表模型中函数
- belongsTo
参数:
- 主键表模型
- 外键表中外键名称
- 主键表中外键名称
例:
一个人只有一种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,human,外键 telephone_id,表2,phone,主键名称 phone_id
// human表模型中
public function AnyFunctionName(){
return $this->hasMany("App\Phones","phone_id","telephone_id");
}
外键表模型中函数
- belongsTo
多对多
主键表模型中函数
- hasMany
外键表模型中函数
belongsToMany
- 主键表模型
- 关联表名称
- 外键表中外键名称
- 关联表中主键表名称
例:
实在想不出例子了,就当表1,主键名称为id1,表模型为Table1Model,表2,主键名称为id2,在两者的关联表中字段名称不变,关联表名称为
Table1_Table2
// 在外键表的模型中
public function AnyFunctionName(){
return $this->belongsToMany('Table1Model','Table1_Table2','id2','id1');
}
另外,创建模型的时候记得设置protected $primaryKey
和protected $table
,有时候找不到表,找不到字段可能就是这个造成的.