代码之家  ›  专栏  ›  技术社区  ›  codex

如何访问yii2中联接表的属性

  •  -2
  • codex  · 技术社区  · 7 年前

    我的控制器中有两个模型(User、ReferralsForm)连接在一起。连接工作正常,但我在访问ReferralsForm中的属性时遇到问题。以下是我的控制器中的代码:

    public function actionReferrals()
    {
        $idOfCurrentUser = Yii::$app->user->identity->id;
        $query = User::find()->joinWith('referrals')->where(['userid' => $idOfCurrentUser])->all();
    
        $model = new User();
        $ref_hash = $model->getHash();
    
        return $this->render('referrals' ,['query' => $query, 'ref_hash' => $ref_hash]);
    }
    

    我的观点:

            (...)
            <table class="table table-hover">
              <tbody><tr>
                <th>#</th>
                <th>Referred Username</th>
                <th>Status</th>
              </tr>
              <tr>
                  <?php foreach ($query as $result){ ?>
                <td><?php echo $result->user_id?></td>
                <td><?php echo $result->display_name?></td>
                <td><?php echo $result->status?></td>
                  <?php } ?>
              </tr>
              </tbody>
            </table>
            (...)
    

    下面是我得到的错误:

    Getting unknown property: app\models\User::status
    

    我想访问 status 从ReferrasForm中,它不包括ReferralsForm中的属性,只包括来自用户的属性,即使我已经加入了他们并添加了 all() 我从类似的问题中读到。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Insane Skull    7 年前

    使用 relationName->attributeName

     <td> <?= $result->referrals->status ?> </td>
    

    如果你有 hasMany() 然后你需要循环 $result->referrals 或使用 $result->referrals[0]->status