通过Yii中的多对多关系查找无关的记录

时间:2014-09-13 10:24:10

标签: php mysql sql activerecord yii

我有一个具有以下关系的Orders ActiveRecord

    /**
 * @return array relational rules.
 */
public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
        'tests' => array(self::MANY_MANY, 'Test', 'orderstests(orders_id, test_id)'),
    );
}

具有以下关系的测试ActiveRecord

    /**
 * @return array relational rules.
 */
public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
        'orders' => array(self::MANY_MANY, 'Orders', 'orderstests(test_id, orders_id)'),
    );
}

和许多关系记录

class OrdersTests extends CActiveRecord

我需要获得与特定订单没有关系的所有测试,这是order_id的记录集,test_id对于特定的order_id不存在。

我似乎无法在Yii中找到任何关系查询。

1 个答案:

答案 0 :(得分:0)

找到答案on Yii forum

public static function getTestsNotInOrder($order)
{
    $excludedTestIds = array_keys($order->tests); // This makes use of the index attribute above

    $criteria = new CDbCriteria();
    $criteria->addNotInCondition('id', $excludedTestIds);

    return self::model()->findAll($criteria);
}