首页 > 解决方案 > Laravel 从关系中只得到一列

问题描述

我有一个表 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"

    },
    {..}
]

用户儿童模型:

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

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

标签: laravelormeloquentrelation

解决方案


您可以使用此代码

$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


推荐阅读