gpt4 book ai didi

php - 有什么办法可以最大限度地减少这段代码的 Mysql 数据库访问吗?

转载 作者:搜寻专家 更新时间:2023-10-30 20:31:17 25 4
gpt4 key购买 nike

我有一个名为 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();
}
}
}

上面的代码将运行一个循环并频繁访问数据库以插入记录。无论如何我可以减少行程并将其最小化为一个吗?

最佳答案

你可以做一个多值插入(至少对于 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)

关于php - 有什么办法可以最大限度地减少这段代码的 Mysql 数据库访问吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6235545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com