Laravel 仅从关系中获取一列

Laravel get only one column from relation

我有一个 table user_childrens,其中包含 id_parent 和 id_user。 我正在尝试列出 parent 的所有 childrens:

代码:

//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();

return是:

[
    {
        "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 所以我只想要 child 列,例如:

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

    },
    {..}
]

用户子模型:

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

我知道我可以通过集合上的 .map() 来做到这一点,但也许这个查询已经有其他解决方案

您可以使用此代码

$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