简体   繁体   English

在yii2中使用Join时结果错误

[英]Wrong results when using Join in yii2

I am trying to get data through find() 我正在尝试通过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 . 我在email字段中得到的全部是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. 您正在使用ActiveRecord,但您加入的状态却不像ActiveRecord那样。 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']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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