CakePHP:belongsTo为null值

时间:2013-06-29 18:22:28

标签: cakephp model foreign-keys relational-database belongs-to

我有一个具有belongsTo关系的模型,这是不需要的。

Banana belongsTo Basket
banana.basket_id can be null

这意味着香蕉可以属于一个篮子,但不是必须的。

保存操作Banana->save(array('Banana' => array('basket_id' => null, 'weight' => 50)));正常,但是当我读到时,我得到了这个结果:

array(
   'Banana' => array('id' => 10, 'basket_id' => null, 'weight' => 50),
   'Basket' => array('id' => null, 'bannana_count' => null)
)

当然,我可以在afterFind中过滤掉它,但如果basket_id为null,我宁愿看到结果数组中没有Basket。怎么办?

使用CakePHP 2.3.6。

2 个答案:

答案 0 :(得分:3)

由于模型使用LEFT JOIN来检索与belongsTo关系相关的模型数据,因此相关字段的值正是您在具有空外键值的选择结果中获得的值 - 每列中的空值。

解决方案是从afterFind回调中的结果数组中过滤这些相关模型。

//Banana model

public function afterFind($results, $primary = false){
   if (isset($results['Basket']) && $results['Basket']['id'] === null) {
      unset($results['Basket']);
   }
   if (isset($results[0])){
       foreach($results as $key => $value){
          if (isset($value['Basket']) && $value['Basket']['id'] === null){
             unset($results[$key]['Basket']);
          }
       }
   }

   //If you forget this, nothing will happen...
   return $results;
}

当然,您可能希望将其设置为false而不是取消设置,或者可能是一个空数组,但由于我没有找到任何约定,因此建议最受欢迎。

答案 1 :(得分:-1)

使用关联中的type键强制进行INNER连接,而不是默认的LEFT连接。

class Banana extends AppModel {
    public $belongsTo = array(
        'Basket' => array(
            'type'  => 'inner',
            'conditions' => array('Banana.basket_id = Basket.id')
        )
    );
}

文档:http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#belongsto