首页 文章

Yii2:如何进行简单的连接查询?

提问于
浏览
0

我正在学习如何使用Yii2框架进行简单查询 . 我使用PostgreSQL .

我正在尝试 join 两个表,并使用 where 条件从两个表中获取数据 .

这些表称为 AdminsPersons . 连接使用字段名为 idadm .

条件是 idadm = 33 . 这很好但结果只有来自Admins表的数据,我需要来自另一个表的数据 .

这是我的例子:

$query = \app\models\Admins::find()
    ->select('*')
    ->leftJoin('persons', 'persons.idadm = admins.idadm')
    ->where(['admins.idadm' => 33])
    ->with('persons')
    ->all();

我正在关注Yii2官方指南:http://www.yiiframework.com/doc-2.0/guide-db-active-record.html

更新:这里我显示了无法解决问题的更新代码:
enter image description here

2 回答

  • 0

    您需要在select()中写入所有列名 .

    $query = \app\models\Admins::find()
        ->select('admin.*,persons.*')  // make sure same column name not there in both table
        ->leftJoin('persons', 'persons.idadm = admins.idadm')
        ->where(['admins.idadm' => 33])
        ->with('persons')
        ->all();
    

    您还需要在Admin模型中定义人员表属性 .

    第二种方法是将记录作为数组,因此您不需要在Admin模型中定义属性 .

    $query = \app\models\Admins::find()
        ->select('admin.*,persons.*')  // make sure same column name not there in both table
        ->leftJoin('persons', 'persons.idadm = admins.idadm')
        ->where(['admins.idadm' => 33])
        ->with('persons')
        ->asArray()
        ->all();
    
  • 1

    确保活动记录需要关系,例如如下所示:

    class Admins extends \yii\db\ActiveRecord {
        public function table() { 
            return "admins";
        }
        public function getPersons() 
        {
            return $this->hasMany(Person::className(), ['idadm' => 'idadm']);
        }    
    }
    
    class Person  extends \yii\db\ActiveRecord { 
        public function table() {
            return "persons";
        }    
    }
    

    然后使用joinWith构建查询:

    $query  = Admins::find()
               ->joinWith('persons')
               ->limit(1);
    
    $result = $query->createCommand()->getSql();
    echo $result;
    

    这是 生产环境 查询:

    SELECT `admins`.* FROM `admins` 
    LEFT JOIN `person` ON `admins`.`idadm` = `person`.`idadm` LIMIT 1
    

相关问题