计算当前的HABTM关系。 CakePHP的

时间:2014-01-05 01:12:24

标签: cakephp has-and-belongs-to-many cakephp-2.4

我需要将医院分配到一个小组。我决定通过habtm这样做。

class FavoriteHospital extends AppModel {
    public $actsAs = array('Containable');
    ...

    var $hasAndBelongsToMany = array(
        'Hospital' => array(
            'className' => 'Hospital',
            'joinTable' => 'favorite_hospitals_hospital',
            'foreignKey' => 'favorite_hospital_id',
            'associationForeignKey' => 'hospital_id',
            'unique' => false,
        )
    );
}

需要将组中的医院数量限制为10.因此,我将关联设置为false,因为默认行为只会删除关联。我决定首先测试使用方法添加医院的能力....

public function addHospital($gid, $hid) {                           
    $this->data['Hospital']['id'] = $hid;
    $this->data['FavoriteHospital']['id'] = $gid;
    if($this->save($this->data)){return true;}
    return false;
}

现在,上面正确地添加了关联,这很好,但每当我试图找到一种方法来计算现有关联的数量时,我就会碰壁。

上面有一个次要问题,那就是它也允许重复。

1 个答案:

答案 0 :(得分:0)

我想出了一个非常非蛋糕的方式(也允许潜在的SQL注入):

public function addHospital($gid, $hid) { 
    $db = $this->getDataSource();
    //$fh_count = $this->query("SELECT count(favorite_hospital_id) FROM favorite_hospitals_hospital WHERE favorite_hospital_id = ".$gid.";");
    $fh_count = $db->fetchAll(
            'SELECT count(favorite_hospital_id) from favorite_hospitals_hospital where favorite_hospital_id = ?',
            array($gid)
    );
    if($fh_count[0][0]['count(favorite_hospital_id)'] < 10){    
        //$existing_association = $this->query("SELECT count(*) FROM favorite_hospitals_hospital WHERE favorite_hospital_id = ".$gid." AND hospital_id = ".$hid.";");
        $existing_association = $db->fetchAll(
                        'SELECT count(*) from favorite_hospitals_hospital where favorite_hospital_id = ? and hospital_id = ?',
                        array($gid,$hid)
        );
        if($existing_association[0][0]['count(*)'] < 1){                    
            $this->data['Hospital']['id'] = $hid;
            $this->data['FavoriteHospital']['id'] = $gid;
            if($this->save($this->data)){return true;}
        } else {
            throw new Exception(__('Association already exists in that group'));
        }
    } else {
        throw new Exception(__('Already 10 Hospitals in that group'));
    }
    return false;
}

有人可以改进这个答案吗?要么让它更像cakephp,要么至少让它更安全?

编辑通过使用数据源对象使其卫生,虽然我仍然觉得这个答案不是最好的答案......