Filter on laravel pivot table
Question
I have two tables in Laravel
connected with a pivot table. The two tables are users
and roles
, and the pivot table is called role_user
. The pivot table also contains two extra fields: start
and stop
. This way I can track which roles a user
has had in the past.
Now I want to create a query that gets all users
who currently have role_id = 3
.
First I had used WherePivot
, but apparently that is bugged.
I have now made the following query using Eloquent
:
Role::with('User')
->where('id', '=', '3')
->where('role_user.start', '<', date('Y-m-d'))
->where('role_user.stop', '>', date('Y-m-d'))
->whereHas('users', function($q){
$q->where('firstname', 'NOT LIKE', '%test%');
})
->get();
But somehow I am getting an error that the column start of the pivot table cannot be found. But I can confirm in PHPMyAdmin
that the column is there.
This is the entire error:
Illuminate \ Database \ QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'klj_role_user.start' in 'where clause' (SQL: select * from `klj_roles` where `id` = 3 and `klj_role_user`.`start` < 2014-06-02 and `klj_role_user`.`stop` > 2014-06-02 and (select count(*) from `klj_users` inner join `klj_role_user` on `klj_users`.`id` = `klj_role_user`.`user_id` where `klj_role_user`.`role_id` = `klj_roles`.`id` and `firstname` NOT LIKE %test%) >= 1)
Can someone tell me if I am doing something wrong or give me a hint where I should be looking now?
Solution
The error is telling you that you are missing the start
column in your pivot table klj_role_user
. What you should do is create the column. If the column is already there, ensure you are using the correct database.
I've also simplified your query a little bit. You don't really need a whereHas
because you aren't trying to limit your roles by the users associated, but by the id, which in this case, you are using 3
. A with()
would work perfectly fine and wherePivot()
seems to be working fine for me when used in conjunction with with()
.
$role = Role::with(array('users' => function($q)
{
$q->wherePivot('start', '>', date('Y-m-d H:i:s'));
$q->wherePivot('stop', '<', date('Y-m-d H:i:s'));
$q->where('firstname', 'NOT LIKE', '%test%');
}))->find(3);
foreach($role->users as $user) {
echo $user->firstname;
}