Domanda

Ho due tabelle in Laravel collegate con una tabella per pivot. Le due tabelle sono users e roles e la tabella pivot è chiamata role_user. La tabella pivot contiene anche due campi extra: start e stop. In questo modo posso tracciare quali ruoli un user ha avuto in passato.

Ora voglio creare una query che ottiene tutti i users che attualmente hanno role_id = 3.

Prima avevo usato WherePivot, ma a quanto pare che bugged .

Ora ho effettuato la seguente query usando 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();
.

Ma in qualche modo ricevo un errore che non è possibile trovare l'inizio della colonna della tabella pivot. Ma posso confermare in PHPMyAdmin che la colonna è lì.

Questo è l'intero errore:

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)
.

Qualcuno può dirmi se sto facendo qualcosa di sbagliato o dammi un suggerimento dove dovrei guardare ora?

È stato utile?

Soluzione

L'errore ti sta dicendo che ti manca la colonna start nella tabella PIVOT klj_role_user.Cosa dovresti fare è creare la colonna.Se la colonna è già lì, assicurati di utilizzare il database corretto.

Ho anche semplificato il tuo query un po '.Non hai davvero bisogno di un whereHas perché non stai cercando di limitare i tuoi ruoli da parte degli utenti associati, ma dall'ID, che in questo caso stai utilizzando 3.Un with() funzionerebbe perfettamente bene e wherePivot() sembra funzionare bene per me quando viene utilizzato in combinazione con 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;
}
.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top