如何在Laravel Eloquent Jensseger Mongodb中使用Get on Eager-loaded属性

时间:2018-05-13 01:01:12

标签: php eloquent eager-loading jenssegers-mongodb

我正在使用Laravel和jenssegers Mongodb Eloquent。当我尝试使用get([...])或distinct('...')时,它会在结果中给出null值。如何使用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
    }
]

1 个答案:

答案 0 :(得分:0)

使用此:

->get()->pluck('sender');

如果您需要查询构建器:

$senderIds = Message::distinct('sender_id')
    ->where('sender_id', '=', Auth::user()->_id)
    [...]
    ->pluck('sender_id');
$senders = Sender::whereKey($senderIds)
    [...]
    ->get();