Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Data Model Questions /

S3: DataObject $MyObject->add($newObject) problem in $many_many relationship


Reply


3 Posts   473 Views

Avatar
Lucas1313

Community Member, 2 Posts

1 December 2012 at 6:53am

Edited: 01/12/2012 6:55am

I am trying to programmatically add a DataObject to another one in a $many_many / $belong_many_many relationahip.

//Object 1
<?php
class ProductSubCategory extends DataObject {
   
   static $db = array(
      'Name' => 'Text',
      'Description' => 'Text',
      'RemoteIndexId'=>'varchar',
      'LegalName' => 'Text',
      'CodeName' => 'Text'
);
static $many_many = array('Ingredients'=>'Ingredient');

function addIngredients($ingredientsArray){

   foreach($ingredientsArray as $k=>$value){
         $newIngredient = new Ingredient();
         $newIngredient->RemoteIndexId = $value->id;
         $newIngredient->Name = $value->name;
         $newIngredient->CodeName = $value->code_name;
         $newIngredient->Description = $value->description;                  
         $this->Ingredients()->add($newIngredient);
      }
   }

}
//Object 2
<?php
class Ingredient extends DataObject {
   static $db = array(
      'Name' => 'Text',
      'RemoteIndexId'=>'Varchar',
      'ScientificName' => 'Text',
      'Description'=>'Text',
      'Percentage'=>'Varchar',
      'CodeName'=>'Varchar'
   );

   static $belong_many_many = array('ProductSubCategory' => 'ProductSubCategory');


//....(some fields for the UI)...
}

Problem description:
a) Ingredients are not being written in the Database.
b) The table ProductSubCategory_Ingredient gets records but they include only the id for ProductSubCategoryID, not IngredientID
c) NO error message

I have been looking around for a solution for days now, at no avail :(
Please help!

Avatar
Willr

Forum Moderator, 5513 Posts

2 December 2012 at 5:21pm

You may need to call $newIngredient->write() before you add it to the relation.

Avatar
Lucas1313

Community Member, 2 Posts

2 December 2012 at 7:18pm

Edited: 02/12/2012 7:19pm

Thank you very much Willr, I will try this first thing Monday when I go back to work at The Clorox Company.