yii2从关系表中选择列遇到问题

时间:2017-09-08 10:13:17

标签: yii2 yii2-advanced-app yii2-basic-app

我想选择所有devlopers表数据,只有User表中的“username”列

我写这个,但我得到错误

$model = Developers::find()->select('*')->with(['users' => function($q){
            $q->select('username');
        }])->asArray()->all();

my Developers“developer_id”列与User table id列有关系 所以我在开发者模型中写过

 public function getUsers()
    {
        return $this->hasOne(User::className(), ['id' => 'developer_id']);
    }

错误是

PHP Notice 'yii\base\ErrorException' with message 'Undefined index: id' 

in /srv/http/adone/vendor/yiisoft/yii2/db/ActiveRelationTrait.php:501

Stack trace:
#0 /srv/http/adone/vendor/yiisoft/yii2/db/ActiveRelationTrait.php(501): yii\base\ErrorHandler->handleError(8, 'Undefined index...', '/srv/http/adone...', 501, Array)
#1 /srv/http/adone/vendor/yiisoft/yii2/db/ActiveRelationTrait.php(381): yii\db\ActiveQuery->getModelKey(Array, Array)
#2 /srv/http/adone/vendor/yiisoft/yii2/db/ActiveRelationTrait.php(245): yii\db\ActiveQuery->buildBuckets(Array, Array)
#3 /srv/http/adone/vendor/yiisoft/yii2/db/ActiveQueryTrait.php(174): yii\db\ActiveQuery->populateRelation('users', Array)
#4 /srv/http/adone/vendor/yiisoft/yii2/db/ActiveQuery.php(214): yii\db\ActiveQuery->findWith(Array, Array)
#5 /srv/http/adone/vendor/yiisoft/yii2/db/Query.php(214): yii\db\ActiveQuery->populate(Array)
#6 /srv/http/adone/vendor/yiisoft/yii2/db/ActiveQuery.php(135): yii\db\Query->all(NULL)
#7 /srv/http/adone/controllers/admin/SiteAdminController.php(30): yii\db\ActiveQuery->all()
#8 [internal function]: app\controllers\admin\SiteAdminController->actionViewDevelopers()
#9 /srv/http/adone/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#10 /srv/http/adone/vendor/yiisoft/yii2/base/Controller.php(156): yii\base\InlineAction->runWithParams(Array)
#11 /srv/http/adone/vendor/yiisoft/yii2/base/Module.php(523): yii\base\Controller->runAction('view-developers', Array)
#12 /srv/http/adone/vendor/yiisoft/yii2/web/Application.php(102): yii\base\Module->runAction('admin/site-admi...', Array)
#13 /srv/http/adone/vendor/yiisoft/yii2/base/Application.php(380): yii\web\Application->handleRequest(Object(yii\web\Request))
#14 /srv/http/adone/web/index.php(12): yii\base\Application->run()
#15 {main}

为什么会这样?

1 个答案:

答案 0 :(得分:2)

试试这个:

Developers::find()->select('developers.*, user.username')->joinWith(['users'])->asArray()->all()