我的数据库中有一对多的关系模型。例如,一个属性有多个价格:
property 1 => $200, $300
property 2 => $200, $350
etc.
这是如何创建属性的:
$prices = array();
$property = new Property();
$property->setName('property 3');
$data_prices = array(200,300,400);
foreach ($data_prices as $price {
$prc = new Price();
$prc->setPrice($price);
$prices[] = $prc; #object collection
}
$property->setPrices($prices);
$property->save();
#codes above create new records on table property and prices (related) and property id = 1
但是当我尝试更新时:
$prices = array();
$property = PropertyQuery::create()->findOneByPropertyId(1);
#create new prices
$data_prices = array(10,20,30);
foreach ($data_prices as $price) {
$prc = new Price();
$prc->setPrice($price);
$prices[] = $prc; #object collection
}
$property->setPrices($prices);
$property->save();
而不是删除旧的价格记录或更新它们,Propel创建新的记录。我想删除旧的价格记录,因为我不需要它们,或者,如果我可以用新价格更新旧价格,那就太棒了。
如何在Propel中执行此操作?
答案 0 :(得分:1)
将Price对象声明为新对象 - 创建新的Price对象。您需要从Property对象调用Price对象或在foreach循环中加载Price对象。由于我不知道您的Price表的结构,我只能给您以前的解决方案:
$prices = array();
$property = PropertyQuery::create()->findOneByPropertyId(1);
$prices = $property->getPrices();
$data_prices = array(10,20,30);
for ($i = 0; $i < count($data_prices); $i++) {
if (!isset($prices[$i])) {
$prc = new Price();
$prc->setPrice($price);
$prc->save();
$prices[] = $prc;
} else {
$prc = $prices[$i];
$prc->setPrice($data_prices[$i]);
$prc->save();
}
}
$property->save();