2

I'm having a hard time resolving this error.

My models:

User Model:

class User extends Model{ public function requests() { return $this->hasMany('App\Models\TeamRequest','requested_user_id'); } } 

TeamRequest Model:

class TeamRequest extends Model { public function requested_user() { return $this->belongsTo('App\Models\User', 'requested_user_id'); } } 

Now, I am trying this query:

UserModel::whereHas('requests',function($query) use ($team_id){ $query->where('team_id',$team_id) ->get(); }); 

And, I'm getting an error:

Column not found: 1054 Unknown column 'users.id' in 'where clause' (SQL: select count(*) from team_requests where team_requests.requested_user_id = users.id)

Why am I getting this error?

Schema:

users table

primary key - id

varchar - email

varchar - password

team_requests table

primary key - id

integer - requested_user_id

I have other columns but I believe they do are not of effect.

7
  • There, I added the schema Commented Feb 20, 2016 at 21:45
  • Actually, I am making a sort of friend request and accept type of application. So, this is what I used. Commented Feb 20, 2016 at 21:50
  • @JilsonThomas I tried but still got an error - unknown column users.requested_user_id Commented Feb 20, 2016 at 21:50
  • yes, that is what most amusing and irritating. Commented Feb 20, 2016 at 21:54
  • Same error. Looks like entire PHP is plotting against me. :/ Commented Feb 20, 2016 at 22:01

1 Answer 1

7

Your problem is that you're calling get() inside the closure passed to your whereHas(). The closure is used to add constraints to a subquery that will be used to determine if your user has requests. You're only supposed to add constraints to the query inside the closure, you don't want to actually execute that query. If you execute the query inside the closure, you'll get an error (as you've seen) because it is supposed to be a subquery, and does not have all the information required to execute properly.

Your code should be:

UserModel::whereHas('requests', function ($query) use ($team_id) { $query->where('team_id', $team_id); }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.