We use cookies to improve your experience. No personal information is gathered and we don't serve ads. Cookies Policy.

ExpressionEngine Logo ExpressionEngine
Features Pricing Support Find A Developer
Partners Upgrades
Blog Add-Ons Learn
Docs Forums University
Log In or Sign Up
Log In Sign Up
ExpressionEngine Logo
Features Pro new Support Find A Developer
Partners Upgrades
Blog Add-Ons Learn
Docs Forums University Blog
  • Home
  • Forums

Updating Pivot Table When Deleting a Related Model

Development and Programming

Richard Whitmer's avatar
Richard Whitmer
96 posts
9 years ago
Richard Whitmer's avatar Richard Whitmer

Model Services question:

I’ve got the hang of Models and relationships in the new services, but I haven’t been able to figure out the best way to update a pivot table after deleting a related item.

For example: I have three tables: menu_items, item_options, and the pivot table menu_items_related.

I have models for the menu_items and item_options tables. It seems like if I have the $_relationships set up in each of the models, the pivot table should be updated when a row in either of the related tables is deleted, but that’s not happening.

Does anyone have this figured out? Can you share an example?

Thanks!

       
Richard Whitmer's avatar
Richard Whitmer
96 posts
9 years ago
Richard Whitmer's avatar Richard Whitmer

This appears to work…

In a model with the pivot table relationship declared,

  1. Create a beforeDelete event.
  2. In the onBeforeDelete function declare the relationship null and save.
class MenuItem extends Model {

  protected static $_primary_key = 'menu_item_id';
  protected static $_table_name = 'menu_items';

  protected static $_relationships = array(
    'ItemOption' => array(
     'type' => 'HasAndBelongsToMany',
     'pivot' => array('table'=>'pivot_table_name',
         'left'=>'menu_item_id',
         'right'=>'item_option_id'),
    )
   );

   protected static $_events = array('beforeDelete');
   
   protected $menu_item_id;
   protected $item;
   protected $description;
   protected $price;
   protected $notes;
  

 public function onBeforeDelete()
 {
    $this->ItemOption = NULL;
    $this->save();
 }
   
}
       

Reply

Sign In To Reply

ExpressionEngine Home Features Pro Contact Version Support
Learn Docs University Forums
Resources Support Add-Ons Partners Blog
Privacy Terms Trademark Use License

Packet Tide owns and develops ExpressionEngine. © Packet Tide, All Rights Reserved.