is there any way i could minimize the Mysql database trip for this piece of code?
i have a table called propAmenities
which holds two column amenity_id
and property_id
basically the table holds the foreign keys.
now i have two insert data into this table, and while inserting data property_id
column will have the same value for all rows that are to be inserted while amentiy_id
value will vary, now for example the values may look like
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);
and the current code to insert the data i am using is:
public function savePropAmenities($amenityIds = array()) {
if($this->validateRequired(array('propertyId'))) {
foreach($amenityIds as $amenityId) {
$sth = $this->dbh-&开发者_运维百科gt;prepare('INSERT INTO
propAmenities
(amenity_id, property_id)
VALUES
(:amenityId, :propertyId)');
$sth->bindParam(':amenityId', $amenityId);
$sth->bindParam(':propertyId', $this->data['propertyId']);
$sth->execute();
}
}
}
the above code will run a loop and will make a frequent trip to database to insert the records. is there anyway i could cut of the trip and minimize it to one?
You can do a multi value insert (for MySQL atleast)
INSERT INTO propAmenities (amenity_id, property_id) VALUES (1, 1), (2, 1), (3, 1)
Also you can set a default value for the field on the database.
ALTER propAmenities MODIFY COLUMN property_id INT DEFAULT 1;
Then you could do this
INSERT INTO propAmenities (amenity_id) VALUES (1), (2), (3)
Not a reduce-to-one answer but heres how to make it more efficient:
Move
$sth = $this->dbh->prepare('INSERT INTO
propAmenities
(amenity_id, property_id)
VALUES
(:amenityId, :propertyId)');
$sth->bindParam(':propertyId', $this->data['propertyId']);
out of the for loop. There is no need to call it multiple times. This should reduce some traffic.
EDIT
so your code becomes
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();
}
}
}
精彩评论