简体   繁体   中英

Laravel how to get users based on model exists or not

In my laravel -application I want to display a list of all users/candidates. So far I have this, which basically works fine:

public function candidates()
{
    $users = User::whereHas(
        'roles',
        function ($q) {
            $q->where('slug', 'candidates');
        }
    )->get();

    return response(['success' => true, "users" => $users], 200);
}

Now, I actually want to display users/candidates who have taken an education. I have a Model called UserEducation but I don't really know to include it to get the data out I want.

can someone help me out?

EDIT

In my User model, I have this relation:

public function educations()
{
    return $this->hasMany('App\Models\UserEducation');
}

you can use has :

 $users = User::has('UserEducation')->whereHas(
        'roles',
        function ($q) {
            $q->where('slug', 'candidates');
        }
    )->get();

You can try create relationship with User and UserEducation models and then get data. https://laravel.com/docs/7.x/eloquent-relationships

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM