yn1043
yn1043

Reputation: 588

How to get the data that has all relation datas specified

I'm building app with laravel.

What I want to do is to get users data with all qualifications specified in the search condition, and display the users list.

This is my model structure.

User:

id  name
1   John
2   Jack

Qualification:

id   name
11   A
12   B
13   C

Qualification_User:

qualification_id   user_id
11                 1
11                 2
12                 2
13                 2

If Setting a search condition "Qualification 11,12,13",

John has only 11 -> not listed.

Jack has all of the qualifications -> listed

I would like to implement this with a laravel query builder, Is there any way?

User.php

public function qualifications()
{
  return $this->belongsToMany('App\Qualification');
}

Controller

$query = App\User::query();
// other condition
// ....

// the case listed if one condition is matched
// but, this is not what I want to do
$query->whereHas(
    'qualifications',
    function ($query) use ($conditions) { //$conditions = [11,12,13]
      $query->whereIn('qualifications.id', $qualifications);
    }
  );

Upvotes: 0

Views: 54

Answers (1)

mutas
mutas

Reputation: 359

In your User model:

public function qualifications()
{
    return $this->belongsToMany(
        Qualification::class,
        'qualification_user',
        'user_id',
        'qualification_id'
    );
}

Then in the controller, assuming you got qualification ids as an array:

$query = User::query();
foreach($qualificationIds as $id) {
    $query->whereHas('qualifications', function ($q) use ($id) {
        $q->where('id', $id);
    });
}
$query->get();

Upvotes: 2

Related Questions