简体   繁体   中英

Wrong results when using Join in yii2

I am trying to get data through find()

This is my code:

 $query = Users::find()->where("is_deleted = '0'")->join('INNER JOIN', 'roles', 'users.role = roles.id')->join('INNER JOIN', 'email_list' , 'users.email = email_list.id')->select('users.name , users.user_name , email_list.email ,roles.name role');

And all I got in email field is 0 .

I tested the DB and there is true emails.

The grid code:

GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'name',
'user_name',
'email:email',
'role',
['class' => 'yii\grid\ActionColumn'],
],
]);

Why is this ? How to fix it ?

You are using ActiveRecord but you join are not as ActiveRecord shouold be. Create relations in models for each join:

public function getRoles()
{
    return $this->hasMany(Role::className(), ['user_id' => 'id']);
}

public function getEmailLists()
{
    return $this->hasMany(EmailList::className(), ['user_id' => 'id']);
}

And use it like:

Users::find()->joinWith(['roles', 'email_list']);

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