Laravel从关系中仅获得一列

时间:2018-07-07 18:03:54

标签: laravel orm eloquent relation

我有一个表user_childrens,其中包含id_parent和id_user。 我正在尝试用此列出父母的所有孩子:

代码:

//relation in model via belongsTo
    $idparent = auth('api')->user()->id;
    $list = UserChildren::where('id_parent',$idparent)
        ->with('child:id,name,email')
        ->get();

    return $list->toJson();

返回值为:

[
    {
        "id": 1,
        "id_parent": 1,
        "id_user": 1,
        "created_at": null,
        "updated_at": null,
        "child": {
            "id": 1,
            "name": "Mr. Davin Conroy Sr.",
            "email": "prempel@example.com"
        }
    },
    {
        "id": 4,
        "id_parent": 1,
        "id_user": 2,
        "created_at": null,
        "updated_at": null,
        "child": {
            "id": 2,
            "name": "Krystel Lehner",
            "email": "cernser@example.net"
        }
    }
]

但是它是API,所以我只想要像这样的子列:

[
    {
        "id": 1,
        "name": "Mr. Davin Conroy Sr.",
        "email": "prempel@example.com"

    },
    {..}
]

UserChildren模型:

public function child() {
    return $this->belongsTo('App\User','id_user','id');
}

我知道我可以通过集合上的.map()来执行此操作,但是此查询上可能已经有其他解决方案了

1 个答案:

答案 0 :(得分:0)

您可以使用此代码

$idparent = auth('api')->user()->id;
$childs = User::whereHas('user_childrens', function ($query) use ($idparent) {
    $query->where('id_parent', $idparent);
})->get(['id', 'name', 'email']);

dd($childs->toJson());

用户模型定义user_childrens关系。

public function user_childrens()
{
    return $this->hasMany('App\UserChildren','id_user','id');
} 

另请参阅文档https://laravel.com/docs/5.5/eloquent-relationships#querying-relationship-existence