2

I have a table user_childrens whose contains id_parent and id_user. I'm trying to list all childrens of the parent with this:

code:

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

The return is:

[
    {
        "id": 1,
        "id_parent": 1,
        "id_user": 1,
        "created_at": null,
        "updated_at": null,
        "child": {
            "id": 1,
            "name": "Mr. Davin Conroy Sr.",
            "email": "[email protected]"
        }
    },
    {
        "id": 4,
        "id_parent": 1,
        "id_user": 2,
        "created_at": null,
        "updated_at": null,
        "child": {
            "id": 2,
            "name": "Krystel Lehner",
            "email": "[email protected]"
        }
    }
]

But it's API so I want only the child column like:

[
    {
        "id": 1,
        "name": "Mr. Davin Conroy Sr.",
        "email": "[email protected]"

    },
    {..}
]

UserChildren Model:

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

I know that I could do this via .map() on collection but maybe there is other solution already on this query

3
  • can you show UserChildren model Commented Jul 7, 2018 at 18:07
  • ok, added @Davit Commented Jul 7, 2018 at 18:12
  • I update my answer try it and ask about result Commented Jul 7, 2018 at 18:16

1 Answer 1

1

You can use this code

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

And User model define user_childrens relation.

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

See also docs https://laravel.com/docs/5.5/eloquent-relationships#querying-relationship-existence

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.