我正在将 Laravel 与 jenssegers Mongodb Eloquent 一起使用。当我尝试使用 get([...]) 或 distinct('...') 它在结果中给出空值。如何使用 get([eager_loaded_attribute_here]) 仅获取预先加载的给定属性?
例子:
Message::with(['sender','receiver'])
->where('sender_id', '=', Auth::user()->_id)
->orWhere('receiver_id', '=', Auth::user()->_id)
->orderBy($request->orderBy, $request->orderByDirection)
->skip(intval($request->offset))
->take(intval($request->limit))
->get()
给出:
[
{
"_id": "5abc2ba193782d24996aefda",
"receiver_id": "5abc28bd93782d235238c162",
"text": "Hello!",
"sender_id": "5abc2b8b93782d24996aefd8",
"updated_at": "2018-03-28 23:56:17",
"created_at": "2018-03-28 23:56:17",
"sender": {
"_id": "5abc2b8b93782d24996aefd8",
"name": "Test 5",
"updated_at": "2018-03-29 00:05:48",
"created_at": "2018-03-28 23:55:55"
},
"receiver": {
"_id": "5abc28bd93782d235238c162",
"name": "Test 1",
"updated_at": "2018-04-20 13:26:00",
"created_at": "2018-03-28 23:43:57"
}
},
...
]
但是使用get:
Message::with(['sender','receiver'])
->where('sender_id', '=', Auth::user()->_id)
->orWhere('receiver_id', '=', Auth::user()->_id)
->orderBy($request->orderBy, $request->orderByDirection)
->skip(intval($request->offset))
->take(intval($request->limit))
->get(['sender'])
给出:
[
{
"_id": "5abc2ba193782d24996aefda",
"sender": null,
"receiver": null
},
...
]
同样,当使用 distinct:
$correspondants=Message::with(['sender','receiver'])
->distinct('sender_id')
->where('sender_id', '=', Auth::user()->_id)
->orWhere('receiver_id', '=', Auth::user()->_id)
->orderBy($request->orderBy, $request->orderByDirection)
->skip(intval($request->offset))
->take(intval($request->limit))
->get()
->toArray();
给出:
[
{
"0": "5abc2b8b93782d24996aefd8",
"sender": null,
"receiver": null
}
]