yii活动记录延迟加载

时间:2014-07-18 12:23:15

标签: php yii

Yii 1.1支持的应用程序。我有模型:CustomerAddresses和CustomerAddressTypes。在数据库中,存在具有字段customer_address_type_flags的表customer_addresses。这意味着地址有许多类型(法律,物理等)。标志是通过二进制OR操作创建的,如:

address_type_flags = 1 | 2 | 8; //1,2,8 - address_type_id values.
address_type_flags // 11

在CustomerAddresses活动记录中,我写了这样的关系:

// CustomerAddresses.php (extends CActiveRecord)
...

public function relations()
{
    return array(
        'AddressTypes' => array(
              self::HAS_MANY
            , 'CustomerAddressTypes'
            , ''
            , 'on' => 'AddressTypes.customer_address_type_id & 
                       Addresses.customer_address_type_flags <> 0'
        )
    );
}

我需要在某些代码部分中获取CustomerAddresses模型的实例。我成功地这样做了:

$customer_addresses = CustomerAddresses::model()
    ->with('AddressTypes')
    ->findByPk( 1 );

如果我使用延迟加载,我会收到错误:

$customer_addresses = CustomerAddresses::model()->findByPk( 1 );
// .. some code here ..
$customer_addresses->AddressTypes; // now related records will be loaded!
// ...and error has been received.

更新。完整错误文本:

  

SQLSTATE [42S22]:找不到列:1054未知列   'where子句'中的'Addresses.customer_address_type_flags'。 SQL   执行的语句是:SELECT   AddressTypescustomer_address_type_id AS t1_c0,   AddressTypescustomer_address_type_name AS t1_c1 FROM   customer_address_types AddressTypes在哪里   (AddressTypes.customer_address_type_id&amp;   Addresses.customer_address_type_flags&lt;&gt; 0)

我找到了临时解决方案:

$customer_addresses = CustomerAddresses::model()->findByPk( 1 );
// .. some code here ..
$types_mask = $customer_address->customer_address_type_flags;
$customer_address->AddressTypes = CustomerAddressTypes::model()->findAll(
    'customer_address_type_id & :customer_address_type_mask <> 0',
    array(':customer_address_type_mask' => $types_mask)
);
// works good, but too much extra code than correct lazy loading operation..

如何在我的情况下正确使用具有相关延迟加载的活动记录?

0 个答案:

没有答案