GSTAR
(Omzy83)
October 23, 2013, 1:43pm
1
Suppose I have a activeCheckBoxList called $model->selections
When the user wants to UPDATE their selections, they can view the form which already has their CURRENT selections ticked.
The user then changes their selections and submits the form. In my controller I need to update these selections in the database.
In my Listing model, I have the following relation, which fetches the current selections:
'categories'=>array(self::HAS_MANY, 'ListingCategory', 'listing_id'),
And here is the ListingController code:
$model = $this->loadModel($id);
$selections = array();
// reference the 'categories' relation
foreach($model->categories as $category)
{
$selections[] = $category->category_id;
}
// $model->selections is a virtual attribute in Listing model
$model->selections = $selections;
if(isset($_POST['Listing']))
{
$model->attributes = $_POST['Listing'];
if($model->validate())
{
foreach($model->selections as $selection)
{
$listing_category = new ListingCategory();
$listing_category->listing_id = $model->id;
$listing_category->category_id = $selection;
$listing_category->save();
}
$this->redirect(array('view', 'id'=>$model->id));
}
}
So this basically ADDS the new selections to the database, but does not delete the existing ones. What is the most efficient way of doing this?
konapaz
(Konapaz)
October 23, 2013, 2:16pm
2
Hi
You have to detect the difference old and news categories
So get the current stored categories($this->oldCategories) and compares with news ($this->newCategories)
Like that
$toRemove = array_diff($this->oldCategories, $this->newCategories);
foreach ($toRemove as $item) {
$item->delete();
}
}
dniznick
(Dniznick)
October 23, 2013, 10:34pm
3
The other thing you can do is delete all the user’s associated records and resave them if the history isn’t important.
konapaz
(Konapaz)
October 24, 2013, 12:18pm
4
KonApaz:
Hi
You have to detect the difference old and news categories
So get the current stored categories($this->oldCategories) and compares with news ($this->newCategories)
Like that
$toRemove = array_diff($this->oldCategories, $this->newCategories);
foreach ($toRemove as $item) {
$item->delete();
}
}
I had the same issue before one months for e-shop that I develop,
so I have to solve the assign of products to their categories
Thanks for voting
Hi,change your code like this in your controller:
foreach($model->selections as $selection)
{
$listing_category =ListingCategory::model();
$listing_category->listing_id = $model->id;
$listing_category->category_id = $selection;
$listing_category->save();
}
yes,if you want update your record,you should declare the class like this "$listing_category =ListingCategory::model();" if you want insert a new record,declare the class:"$listing_category =new ListingCategory();",Then call the save method.