1

我正在尝试以 $many_many / $belong_many_many 关系以编程方式将 DataObject 添加到另一个 DataObject 。Silverstripe-3 似乎对该任务有问题。

//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)... 
    }

问题描述: 1. 成分没有被写入数据库。2. 表 ProductSubCategory_Ingredient 获取记录,但它们仅包含 ProductSubCategoryID 的 id,不包含 IngredientID 3. 没有错误消息

我这几天一直在寻找解决方案,但无济于事,
请帮助!

4

2 回答 2

1

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/

于 2012-12-01T00:15:55.660 回答
0

@3dg00 是对的,应该$belongs_many_many带有一个“s”,你还必须打电话

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

在您的 foreach 循环之后,将内容写入数据库。 http://api.silverstripe.org/3.0/framework/model/DataObject.html#methodwrite

于 2013-01-20T10:26:38.603 回答