Jump to:

3447 Posts in 1061 Topics by 738 members

Data Model Questions

SilverStripe Forums » Data Model Questions » S3: DataObject $MyObject->add($newObject) problem in $many_many relationship

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

Page: 1
Go to End
Author Topic: 393 Views
  • Lucas1313
    Avatar
    Community Member
    2 Posts

    S3: DataObject $MyObject->add($newObject) problem in $many_many relationship Link to this post

    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!

  • Willr
    Avatar
    Forum Moderator
    5497 Posts

    Re: S3: DataObject $MyObject->add($newObject) problem in $many_many relationship Link to this post

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

  • Lucas1313
    Avatar
    Community Member
    2 Posts

    Re: S3: DataObject $MyObject->add($newObject) problem in $many_many relationship Link to this post

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

    393 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.