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 /

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

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

Go to End

3 Posts   763 Views


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
class ProductSubCategory extends DataObject {
	static $db = array(
		'Name' => 'Text',
		'Description' => 'Text',
		'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;						

//Object 2
class Ingredient extends DataObject {
	static $db = array(     
		'Name' => 'Text',  
		'ScientificName' => 'Text',

	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!


Forum Moderator, 5523 Posts

2 December 2012 at 5:21pm

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


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.