Yii范围与多表关系

时间:2016-06-07 14:35:42

标签: php mysql yii

我有一个与模型预订有一对多关系的模型订单。反过来,预订模型具有连接模型参考。

我无法弄清楚如何确定Order的范围,这样我才能获得将Connection.isDefault值设置为0的订单。

我订购时可能会有很多预订,所以我需要查看第一次预订。

我觉得这可能无法通过范围机制实现,因为我无法通过可在范围内使用的辅助函数传递Order / Booking主键。您可以在此提出什么替代解决方法(如果有的话)?

订单有一个范围代码: public function scopes() { return array( 'canView' => array( 'with' => array( 'agency' => array( 'scopes' => array('myNetwork', 'myCompany' => 'OR') ) ), ), 'canEdit' => array( 'with' => array( 'agency' => array( 'scopes' => array('myNetwork', 'myCompany' => 'OR') ), ), ), ); }

2 个答案:

答案 0 :(得分:1)

请尝试使用CDbCriteria()。在Bookings表和order表中添加关系。

The Bookings有一个关系代码:

class Bookings extends CActiveRecord{

    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(
            'connectionRel' => array(self::BELONGS_TO, 'connection', 'booking_id', "condition" => 'isDefault = 0'),
        );
    }
}

订单包含关系代码:

class Order extends CActiveRecord{

    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(
            'bookingsRel' => array(self::BELONGS_TO, 'Bookings', 'booking_id', "with" => array('connectionRel')),
        );
    }
}

查找预订关系的所有订单:

Order::model()->with('bookingsRel')->findAll();

答案 1 :(得分:0)

尝试使用CDbCriteria()。在with中,你可以放置关系,然后再进行with(做一些 CDbCriteriaCeption )。尝试尝试其他标准参数以满足您的需求(例如应用$c->together = true;

$c = new CDbCriteria();
$c->with = [
    'bookings' => [
        'select' => false,
        'with' => [
            'connections' => [
                'select' => false,
            ]
        ]
    ]
];
$c->addCondition('connections.isDefault = 0');

Order::model()->findAll($c);