【发布时间】:2020-09-08 19:29:03
【问题描述】:
我在 UsersApiController 类中有以下函数:- 公共函数 getKhatmas()
{
$user = Auth::user();
$khatmas = $user->khatmas;
return response()->json($khatmas);
}
上面的代码给出以下响应:-
[
{
"id": 3,
"hash": "5ec72b4913d1a",
"type": 2,
"type_text": "sample text",
"division": 2,
"division_variant": 1,
"status": "active",
"expiry_date": null,
"is_name": 0,
"user_id": 2,
},
{
"id": 4,
"hash": "5ec72b7005126",
"type": 2,
"type_text": "sample text",
"division": 2,
"division_variant": 1,
"status": "active",
"expiry_date": null,
"is_name": 0,
"user_id": 2,
},
]
用户模型文件中的关系函数:-
public function khatmas()
{
return $this->hasMany('App\Khatma');
}
App\Khatma 文件内容:-
public function type()
{
return $this->belongsTo('App\KhatmaType');
}
在上面的 json response 中,("type": 2) 是 App\KhatmaType Model 的外键。 我希望使用 KhatmaType 模型的外键而不是 json 响应,我希望它从 App\KhatmaType 返回列“标题”,如下所示:-
{
"id": 3,
"hash": "5ec72b4913d1a",
"type": "this is title from App\KhatmaType Model",
"type_text": "sample text",
"division": 2,
"division_variant": 1,
"status": "active",
"expiry_date": null,
"is_name": 0,
"user_id": 2,
}
`我尝试了以下方法:-
$khatmas = $user->khatmas->with('type');
但它返回错误:方法 Illuminate\Database\Eloquent\Collection::with 不存在
【问题讨论】:
-
你可以试试这个
Auth::user()->load('khatmas.type') -
@Aslam 我试过了,我得到了 "type": null,
-
你可以在查询中使用join,但我认为你有反向定义的关系,或者错误表中的外键'type',因为如果KhatmaType属于Khatma,外键应该在KhatmaType 而不是在 Khatma 中。