2
votes

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.

1
There, I added the schema - Faizuddin Mohammed
Actually, I am making a sort of friend request and accept type of application. So, this is what I used. - Faizuddin Mohammed
@JilsonThomas I tried but still got an error - unknown column users.requested_user_id - Faizuddin Mohammed
yes, that is what most amusing and irritating. - Faizuddin Mohammed
Same error. Looks like entire PHP is plotting against me. :/ - Faizuddin Mohammed

1 Answers

6
votes

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);
});