【发布时间】:2017-02-14 20:39:58
【问题描述】:
场景是带有表 account、account_contact、contact 和 account_contact_role 的 crm。后者包含诸如“项目负责人”或“客户经理”等角色,用于连接表中定义的组合。
我的挑战是帐户视图,也就是列出关联的人及其角色。我希望我的网格显示:Doe |约翰 |员工。
现在的问题是联系人在联结表中有 2 个以上的条目。如何打印该行的正确角色?正如您在代码中看到的那样,我以静态方式解决了它,它仅显示 n 次中的 1 次正确值。尝试使用内部连接但没有成功。是模型中的搜索问题还是视图中的访问问题?
帐户模型与联系人的关系:
public function getContacts($role = null)
{
// many-to-many
return $this->hasMany(ContactRecord::className(), ['id' => 'contact_id'])
->via('accountContacts')
->innerJoinWith(['accountContacts.role'])
->andWhere(['account_contact.account_id' => $this->id])
->andWhere(['account_contact_role.type' => $role])
;
}
视图
<?= \yii\grid\GridView::widget([
'dataProvider' => new \yii\data\ActiveDataProvider([
'query' => $model->getContacts('internal'),
'pagination' => false
]),
'columns' => [
'lastname',
'firstname',
[
'label' => 'Role',
'attribute' => 'accountContacts.0.role.name',
],
[
'class' => \yii\grid\ActionColumn::className(),
'controller' => 'contacts',
'header' => Html::a('<i class="glyphicon glyphicon-plus"></i> Add New', ['contact-records/create', 'account_id' => $model->id]),
'template' => '{update}{delete}',
]
]
]); ?>
定义的关系是:
帐户有很多 accountContacts 有一个联系人
accountContacts 有一个 accountContactRole
非常感谢!
【问题讨论】:
标签: activerecord yii2