0

I got a problem, When try to use whereHas in this case

Table users.

----------------
| id | name    |
----------------
| 1  | AAA     |
| 2  | BBB     |
| 3  | CCC     |
----------------

Table subjects.

------------------
| id | title     |
------------------
| 1  | Subject 1 |
| 2  | Subject 2 |
------------------

Table subject_user.

------------------------
| user_id | subject_id |
------------------------
| 1       | 1          |
| 2       | 1          |
| 1       | 2          |
| 3       | 2          |
------------------------

in Subject Model

...

public function User()
{
    return $this->belongsToMany(User::class, 'subject_user');
}

...

When I want to find subject by user_id with this query.

In this case Auth::id() == 1 and $request->user_id == 3

$subject = Subject::whereHas('User', function ($query) use ($request) {
    $query->whereIn('user_id', [Auth::id(), $request->user_id]);
})->get();

With this query, I got subjects 1 and 2. That was a wrong result. That must got only subject 2.

Then I try this.

$subject = Subject::whereHas('User', function ($query) use ($request) {
    $query->where('user_id', Auth::id())->where('user_id', $request->user_id);
})->get();

It would not get any subjects.

What query do I use in this case to get only subject 2.

ThunderBirdsX3
  • 558
  • 1
  • 9
  • 25

2 Answers2

1

@Lloople from your answer, I got an idea.

$subject = Auth::user()->Subject()->whereHas('User', function ($query) use ($request) {
    $query->where('user_id', $request->id);
})->first();
ThunderBirdsX3
  • 558
  • 1
  • 9
  • 25
  • This will not work, since first you're filtering the subjects for the current logged in users, so you will search for another user's subjects when you already filtered that with the relation. – Lloople Nov 13 '17 at 10:44
  • @Lloople No that's work. From query I got my subjects first. Then I use all of these to find subject between another user. – ThunderBirdsX3 Nov 14 '17 at 03:58
0

Why not doing it backwards? You already have the logged in user, so if you define the relationship in the User model you can do

$subjects = auth()->user()->subjects;

Anyway, you don't need to check double the Auth::id()and $request->user_id. In fact, I'm not sure you can do this last one.

Edit after comments

$subjects = Subject::whereBetween(auth()->user()->id, $request->user_id)->get();

You will need to change the order from the inputs, in case $request->user_id is less than auth()->user()->idor it wouldn't work.

Lloople
  • 1,827
  • 1
  • 17
  • 31