有什么方法可以最小化这段代码的Mysql数据库之旅吗?

时间:2011-06-04 07:57:21

标签: php mysql database pdo

我有一个名为propAmenities的表,其中包含两列amenity_idproperty_id基本上该表包含外键。

现在我在这个表中有两个插入数据,而插入数据property_id列时,对于要插入的所有行,当amentiy_id值变化时,列将具有相同的值,现在例如值可能看起来像

INSERT INTO propAmenities(amenity_id, property_id) VALUES(1,1);
INSERT INTO propAmenities(amenity_id, property_id) VALUES(2,1);
INSERT INTO propAmenities(amenity_id, property_id) VALUES(3,1);
INSERT INTO propAmenities(amenity_id, property_id) VALUES(4,1);
INSERT INTO propAmenities(amenity_id, property_id) VALUES(5,1);

并且插入我正在使用的数据的当前代码是:

public function savePropAmenities($amenityIds = array()) {
    if($this->validateRequired(array('propertyId'))) {
        foreach($amenityIds as $amenityId) {
            $sth = $this->dbh->prepare('INSERT INTO
                                        propAmenities
                                        (amenity_id, property_id)
                                        VALUES
                                        (:amenityId, :propertyId)');
            $sth->bindParam(':amenityId', $amenityId);
            $sth->bindParam(':propertyId', $this->data['propertyId']);
            $sth->execute();    
        }
    }
}

上面的代码将运行一个循环,并会经常访问数据库以插入记录。无论如何我可以减少旅行并最小化到一个?

2 个答案:

答案 0 :(得分:2)

您可以执行多值插入(至少适用于MySQL)

INSERT INTO propAmenities (amenity_id, property_id) VALUES (1, 1), (2, 1), (3, 1)

您还可以为数据库中的字段设置默认值。

ALTER propAmenities MODIFY COLUMN property_id INT DEFAULT 1;

然后你可以这样做

INSERT INTO propAmenities (amenity_id) VALUES (1), (2), (3)

答案 1 :(得分:0)

不是一个简单的答案,而是如何提高效率:

移动

 $sth = $this->dbh->prepare('INSERT INTO
                                        propAmenities
                                        (amenity_id, property_id)
                                        VALUES
                                        (:amenityId, :propertyId)');
$sth->bindParam(':propertyId', $this->data['propertyId']);

out for for循环。无需多次调用它。这应该减少一些流量。

修改

所以你的代码变成了

public function savePropAmenities($amenityIds = array()) {
    if($this->validateRequired(array('propertyId'))) {
        $sth = $this->dbh->prepare('INSERT INTO
                                        propAmenities
                                        (amenity_id, property_id)
                                        VALUES
                                        (:amenityId, :propertyId)');
        $sth->bindParam(':propertyId', $this->data['propertyId']);
        foreach($amenityIds as $amenityId) {
            $sth->bindParam(':amenityId', $amenityId);

            $sth->execute();    
        }
    }
}