Yii 2过滤联结表中值的多对多关系

时间:2017-01-25 09:47:08

标签: yii yii2 yii2-model

如何在Yii 2.0中使用多对多关系,我在哪里过滤连接/联结表中的值的结果?

我有以下表格

Member (id INT, name, ...)
Event (id INT, name, date, ...)
EventMemberConnection (id INT, event_id INT, member_id INT, accepted TINYINT(1) DEFAULT 0, foreign keys....)

成员通过EventMemberConnection连接到事件,并使用整数表示是否接受或拒绝

从模型文件Event.php:

/**
 * @return \yii\db\ActiveQuery
 */
public function getAcceptedMembers() {
    return $this->hasMany(Member::className(), ['id' => 'member_id'])->viaTable('EventMemberConnection acceptedConnection', ['event_id' => 'id'])->onCondition(['acceptedConnection.accepted' => 1]);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getDeclinedMembers() {
    return $this->hasMany(Member::className(), ['id' => 'member_id'])->viaTable('EventMemberConnection declinedConnection', ['event_id' => 'id'])->onCondition(['declinedConnection.accepted' => 0]);
}

查询,在休息控制器内:

public function prepareDataProvider() {
    $query = Event::find();

    $query->joinWith('acceptedMembers acceptedMember');
    $query->joinWith('declinedMembers declinedMember');

    $query->groupBy(['Event.id']);

    return new ActiveDataProvider([
        'query' => $query
    ]);
}

我正在使用REST API来获取使用acceptedMembers和rejectedMembers扩展的事件对象。我从通话中收到以下数据库错误:

Column not found: 1054 Unknown column 'acceptedConnection.accepted' in 'where clause'
The SQL being executed was: SELECT * FROM `Member` `acceptedMember` WHERE (`id` IN ('5', '9')) AND (`acceptedConnection`.`accepted`=1)

我猜主要查询没问题,但是Yii获取相关成员的额外调用会增加onConnection函数中使用的条件。

我在documentation中读到它只应用于过滤相关表而不是联结表。所以我不相信onCondition是要走的路。

有没有办法过滤关联表中设置的值的关系?

1 个答案:

答案 0 :(得分:3)

我在documentation中发现你可以为viaTable()函数添加一个回调,可以用来自定义连接查询。您可以像这样使用它:

public function getAcceptedMembers() {
    return $this->hasMany(Member::className(), ['id' => 'member_id'])->viaTable('EventMemberConnection acceptedConnection', ['event_id' => 'id'], function($query){
        $query->where(['acceptedConnection.accepted' => 1]);
    });
}