我正在研究Laravel项目,但是关系方面遇到了问题。
我有CarAddress模型和用户模型
在caraddress表中,我有id,sessionId,
在用户表中,我有ID和sessioId。
CarAddress模型中的代码
protected $table = 'caraddress';
public $primaryKey ='id';
function users(){
return $this->belongsTo('App\User','sessionId');
}
用户模型中的代码
public function CarAddress(){
return $this->hasMany('App\CarAddress');
}
控制器代码 $ carAddress = CarAddress :: with('users')-> get(); 返回$ carAddress;
结果为:
[
{
"id": 25,
"sessionId": "dqEeucFqkNzSUQtPxqdxqvJbCqyrAuVXVqIf3y6l",
"residentialStatus": "homeowner",
"addressYears": "1",
"addressMonths": "0",
"totalMonths": "12",
"postcode": "SW1A 2AA",
"buildingNumber": null,
"street": "10 Downing Street",
"town": "London",
"county": null,
"country": null,
"buildingName": null,
"userRefference": "FFD",
"created_at": "2018-10-20 22:30:44",
"updated_at": "2018-10-19 20:18:22",
"users": null
}
]
答案 0 :(得分:3)
如果要在两个表中都连接sessionId,则需要同时指定两个键:
function users(){
return $this->belongsTo('App\User','sessionId', 'sessionId');
}
您的代码还有其他奇怪之处:</ p>
我强烈建议您在此处阅读整个文档:https://laravel.com/docs/5.7/eloquent-relationships