Laravel使用join来获取数据返回null

时间:2017-11-12 05:58:14

标签: php laravel laravel-5.3

在下面的获取数据结果中:

{
    "purchases": [
        {
            "id": 1,
            "member_id": 1,
            "mediator_id": 2,
            "type": null,
            "cash": 38712402,
            "created_at": "2017-11-08 06:40:45",
            "updated_at": "2017-11-08 06:40:45",
            "deleted_at": null,
            "cheques": [
                {
                    "id": 1,
                    "purchase_id": 1,
                    "expire_date": "1396-01-19",
                    "amount": 97094060,
                    "isRejected": 0,
                    "created_at": "2017-11-08 06:40:45",
                    "updated_at": "2017-11-08 06:40:45",
                    "deleted_at": null
                }
            ]
        },
        {
            "id": 2,
            "member_id": 1,
            "mediator_id": 2,
            "type": null,
            "cash": 46760191,
            "created_at": "2017-11-08 06:40:45",
            "updated_at": "2017-11-08 06:40:45",
            "deleted_at": null,
            "cheques": []
        }
    ]
}

我通过这段代码得到了它:

$purchases = \App\Purchase::with('cheques')->where('member_id',
        $request->userId)->get();

我试图从amount cheques'cash','created_at' purchases 'member_id'=$request->userId获取cheques,但我得空$purchases = \App\Purchase::with(array('cheques'=>function($query){ $query->select('amount'); }))->where('member_id',$request->userId)->get(['cash','created_at']); 当我使用这段代码时:

{{1}}

3 个答案:

答案 0 :(得分:1)

你能试试吗?

$purchases = \App\Purchase::with(array('cheques'=>function($query){
    $query->select('id', 'amount', 'purchase_id');
}))->where('member_id',$request->userId)->get(['cash','created_at']);

答案 1 :(得分:0)

尝试文档中的Eager Loading Specific Columns部分 - https://laravel.com/docs/5.5/eloquent-relationships

它说:

  

使用此功能时,您应始终在要检索的列列表中包含id列。

答案 2 :(得分:0)

$purchases = \App\Purchase::with(
    array('cheques' => function($query){
        $query->select('amount');
    })
    )->where('member_id',$request->userId)
    ->select('cash','created_at')->get();

如果要使用get methon of collection选择列,则需要传递id:

->get(['id', 'cash', 'created_at']);或您可以使用->select('cash', 'created_at')->get();

您更喜欢。