简体   繁体   中英

Kohana 2.3.4 ORM - delete pivot table relationships

I'm trying to remove relationships from a pivot table with ORM's remove method. This is for an edit method that updates the categories associated with a product. I can successfully add multiple relationships, but I need to remove those relationships prior to adding them again.

Here's how I add them

           foreach ($categories as $addCat)
              {
                $product->add(ORM::factory('category', $addCat));
              }

$categories is an array of items from a form and $product is the model. This works perfect.

I think I need to do something like this to remove them, but it's not working

$product->remove(ORM::factory('category', $product->id));

$product->id is the id of a product. I am calling this script before the add script. My goal is remove all the relationships that contain the value in "$product->id" and then run my loop to add them again. I could do this easily if I created a model for the pivot table, but that would go against the point of using pivot tables.

You have the right idea. When you call ORM::factory('category', $product->id) you are trying to find a category with the same id as your product. Instead you need to specify the id of the category you want to remove.

Say you have an array of id's of categories that you want to remove:

$categories = array('2', '4', '6');
foreach ($categories as $cat_id)
{
    $product->remove(ORM::factory('category', $cat_id));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM