dimanche 6 mars 2016

How to use "where not" in a Laravel Model Relationship?

I have a user table similar to:

=== users ===
id: int (PK)
name: string
is_coach: bool
...

and a coach request table similar to:

=== coach_requests ===
id: int (PK)
student_id: int(FK => users.id)
coach_id: int(FK => users.id)
...

I also have the corresponding Laravel models (i.e. User and CoachRequest).

In the User model, I wish to make a method such that given a specified user, return all users with is_coach = true, except:

  • him/herself and
  • users who have already been matched with that person as a coach in the coach_requests table.

For example consider the following sample data:

users

(1, "A", false)
(2, "B", true)
(3, "C", true)
(4, "D", true)
(5, "E", true)
(6, "F", true)

coach_requests

(1, 2, 3)
(2, 2, 4)
(3, 3, 2)
(4, 3, 6)
(5, 4, 5)
(6, 4, 6)
(7, 5, 6)
(8, 6, 5)
(9, 1, 4)

Now if I was user with:

  • id 1 (i.e. User "A"), return user ids: 2, 3, 5 and 6
  • id 2, return user ids: 5, 6
  • id 3, return user ids: 4, 5
  • id 4, return user ids: 2, 3
  • id 5, return user ids: 2, 3, 4
  • id 6, return user ids: 2, 3, 4

How can I do this using Laravel???

So far all I have is this:

public function scopeOfFreeCoaches($query) {
    return $query->where([
        'is_coach' => true,
    ]);
}

So not much!

Many Thanks!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire