【问题标题】:correct value instead of array正确的值而不是数组
【发布时间】: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>&nbsp;Add New', ['contact-records/create', 'account_id' => $model->id]),
            'template' => '{update}{delete}',
        ]
    ]
]); ?>

定义的关系是:

帐户有很多 accountContacts 有一个联系人
accountContacts 有一个 accountContactRole

非常感谢!

【问题讨论】:

    标签: activerecord yii2


    【解决方案1】:

    您正在显示帐户的联系人,因此您必须从联系人模型中列出。

    联系人模型(或联系人 ActiveQuery 文件)内部:

    public static function queryContactsFromAccountAndRole($account, $role = null)
    {
        // many-to-many
        return ContactRecord::find()->innerJoinWith(['accountContacts' => function($q) use($account, $role) {
            $q->innerJoinWith(['accountContactsRole'])
            ->andWhere(['account_contact.account_id' => $account->id])
            ->andWhere(['account_contact_role.type' => $role]);
        }]) 
        ->andWhere(['account_contact.account_id' => $account->id]);
    }
    

    现在每个联系人都有一个记录,gridview 将显示所有联系人。

    【讨论】:

    • 像魅力一样工作,谢谢。甚至想我想知道是否真的需要第二个 (->andWhere(['account_contact.account_id' => $account->id]);)?
    • 不,不需要,因为有一个内连接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 2012-09-04
    相关资源
    最近更新 更多