我正在尝试获取具有关系和嵌套字段的用户模型。第一次尝试运行良好:
$user = \App\User::where('id', auth()->user()->id)->with(['userdoc'])->get();
它返回整个userdoc对象。但是我只想要两个字段,所以我在尝试:
$user = \App\User::where('id', auth()->user()->id)->with(['userdoc:id,number'])->get();
通过这种方式,它以userdoc:null
JSON返回toArray()
。
根据https://laravel.com/docs/5.5/eloquent-relationships#eager-loading上的文档,这似乎没问题
我正在使用Laravel 5.6。
添加更多信息:
没有特定字段将获取整个对象
$user = \App\User::where('id', auth()->user()->id)->with('userdoc')->get();
return response()->json($user->toArray(), 200);
[
{
"id": 11,
"email": "xxxxx",
"slug": "xxxxx",
"created_at": "xxxxx",
"updated_at": "xxxxx",
"deleted_at": null,
"first_name": "xxxxx",
"last_name": "xxxxx",
"is_verified": 0,
"userdoc": {
"id": 11,
"created_at": "2018-08-20 13:20:29",
"updated_at": "2018-08-20 13:20:29",
"deleted_at": null,
"user_id": 11,
"type": "document",
"number": "xxxxxxxxx"
}
}
]
确定userdoc
字段会使对象变为空
$user = \App\User::where('id', auth()->user()->id)->with('userdoc:id,number')->get();
return response()->json($user->toArray(), 200);
[
{
"id": 11,
"email": "xxxxxxxxxxx",
"slug": "xxxxxxxxxxx",
"created_at": "xxxxxxxxxxx",
"updated_at": "xxxxxxxxxxx",
"deleted_at": null,
"first_name": "xxxxxxxxxxx",
"last_name": "xxxxxxxxxxx",
"is_verified": 0,
"userdoc": null
}
]
答案 0 :(得分:2)
您需要在以下位置删除括号=Parameters!Deliverable.Value <> "ABC" AND Parameters!Deliverable.Value <> "All"
:
[]
应该是:
$user = \App\User::where('id', auth()->user()->id)->with(['userdoc:id,number'])->get();
_________________________________________________________^___________________^
您也应该在$user = \App\User::where('id', auth()->user()->id)->with('userdoc:id,number')->get();
传递的字段中传递外键:
with
答案 1 :(得分:2)
您得到的结果是因为您没有选择相关的主键user_id
。试试这个
$user = \App\User::where('id', auth()->user()->id)->with(['userdoc:id,user_id,number'])->get();
答案 2 :(得分:2)
我猜测您的userdocs
表具有user_id
属性,并且您正在users
和userdocs
之间使用一对多关系。在这种情况下,您还需要从userdoc
获取外键:
$user = \App\User::where('id', auth()->id())->with(['userdoc:id,number,user_id'])->get();
答案 3 :(得分:1)
我必须将id添加到嵌套的紧急加载中,以获取客户端的名称:
$foo = Visitor_visit::with('client:id,name')->get();
否则,它为空,希望能对某人有所帮助。