Luc Martin
Luc Martin

Reputation: 31

Silverstripe S3: DataObject adding in many_many relationship

I am trying to programmatically add a DataObject to another one, in a $many_many / $belong_many_many relationship. Silverstripe-3 seem to have a problem with that task.

//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: 1. Ingredients are not being written in the Database. 2. The table ProductSubCategory_Ingredient gets records but they include only the id for ProductSubCategoryID, not IngredientID 3. NO error message

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

Upvotes: 1

Views: 2504

Answers (2)

3dgoo
3dgoo

Reputation: 15794

There is a typo in your variable name. You are missing an s in belongs.

This:

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

Should be this:

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

Here is a good resource on many-to-many relationships in SS3:
http://fake-media.com/2014/01/18/silverstripe-3-many-many-a-comprehensive-example/

Upvotes: 1

colymba
colymba

Reputation: 2644

@3dg00 is right, should be $belongs_many_many with an 's' and you'll also have to call

$this->write(null, null, null, true);

after your foreach loop so things get written to the database. http://api.silverstripe.org/3.0/framework/model/DataObject.html#methodwrite

Upvotes: 0

Related Questions