yii2中如何访问连接表的属性
How to access the attributes of the joined tables in yii2
我的控制器中有两个模型(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
我想从 ReferrasForm 访问 status
,但是它不包括 ReferralsForm 的属性,只包括用户的属性,即使我已经加入他们并添加了类似的 all()
我阅读的问题。
使用relationName->attributeName
<td> <?= $result->referrals->status ?> </td>
如果你有 hasMany()
关系那么你需要遍历 $result->referrals
或使用 $result->referrals[0]->status
我的控制器中有两个模型(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
我想从 ReferrasForm 访问 status
,但是它不包括 ReferralsForm 的属性,只包括用户的属性,即使我已经加入他们并添加了类似的 all()
我阅读的问题。
使用relationName->attributeName
<td> <?= $result->referrals->status ?> </td>
如果你有 hasMany()
关系那么你需要遍历 $result->referrals
或使用 $result->referrals[0]->status