gpt4 book ai didi

postgresql - Yii2:如何做一个简单的连接查询?

转载 作者:行者123 更新时间:2023-12-05 01:18:25 25 4
gpt4 key购买 nike

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

我正在尝试加入两个表并使用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

最佳答案

您需要在 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 模型中定义人员表属性。

第二种方式是获取记录作为数组,所以你不需要在管理模型中定义属性。

$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();

关于postgresql - Yii2:如何做一个简单的连接查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46001404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com