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

时间:2017-09-01 13:32:37

标签: postgresql yii2 yii2-advanced-app

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

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

这些表格称为管理员人员。 加入使用字段名为 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 :(得分:1)

您需要在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 :(得分:0)

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

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