我在 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('AppKhatma');
}
应用程序\哈特玛文件内容:-
public function type()
{
return $this->belongsTo('AppKhatmaType');
}
在上面的json响应中,("type": 2(是App\KhatmaType模型的外键。 我想要而不是使用 KhatmaType 模型的外键的 json 响应,我希望它从 App\KhatmaType 返回列"title"是这样的:-
{
"id": 3,
"hash": "5ec72b4913d1a",
"type": "this is title from AppKhatmaType 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');
但它返回错误:方法照明\数据库\雄辩\集合::with 不存在
使用以下查询生成器修复:-
public function getKhatmas()
{
$user = Auth::user();
$khatmas = Auth::user()->khatmas()
->select('hash','type_text','status','expiry_date','type_id')
->with('type')->get();
return response()->json($khatmas);
}