简体   繁体   中英

Column not found - Laravel whereHas error

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM