我多次阅读documentation。
这是表结构:
categories:
id controller user_id approved enabled_comments
categories_related_categories
id category_id related_category_id
categories_zones
id category_id zone_id
这是我的期望:
我想保存多种关系:
期望:
所以这是与父母和区域有关系的子类别:
这是代码:
public function create(){
$vanity_url = new VanityUrl();
$vanity_url->where('url',$this->uri->segment(2))->get();
$blogger = new User();
$blogger->where('id',$vanity_url->user_id)->get();
/* self-referencing many to many */
$subcategory = new Category; //subcategory - we create a new one
$subcategory->controller = $this->input->post('controller');
$subcategory->enable_comments = $this->input->post('approved');
$subcategory->user_id = $this->current_user()->id;
$parent_category = new Category(); //parent category - we find via a search in the table
$parent_category->where('controller',$this->input->post('parent_controller'))->get();
// $subcategory->save($parent_category);
/* many to many - category has many zones :: zone has many categories */
$zone = new Zone();
$zones = $this->input->post('zones');
foreach($zones as $z){
switch($z){
case 'main':
$zone->where('name',$z);
break;
case 'panel':
$zone->where('name',$z);
break;
}
}
$zone->get();
$subcategory->save($parent_category,$zone);
}
我使用上面的代码得到以下错误(虽然categories_zones表确实写入了):
A PHP Error was encountered
Severity: Warning
Message: Illegal offset type in isset or empty
Filename: libraries/Datamapper.php
Line Number: 4151
我试试这个:
$subcategory->save_relation($parent_category,$zone);
但是我收到了这个错误:
An Error Was Encountered
Unable to relate category with relation.
然后我尝试此链接中的示例:http://datamapper.wanwizard.eu/pages/save.html
$subcategory->save(array($parent_category,$zone));
这将写入categories_related_categories表而不是categories_zones表。
我的类别和区域模型包含:
class Category extends DataMapper {
var $has_one = array("user");
public $has_many = array(
'related_category' => array(
'class' => 'category',
'other_field' => 'category',
// 'reciprocal' => TRUE
),
'category' => array(
'other_field' => 'related_category',
),
'post',
'zone'
);
}
class Zone extends DataMapper {
var $has_many = array("category");
}
我的临时解决方案是最后一条评论(截至目前): http://codeigniter.com/forums/viewthread/186054/
答案 0 :(得分:0)
我知道这是一个老问题,但我会尝试用这个问题帮助其他人。
当您保存多个关系时,您可以(并且必须在自引用关系中)使用您在模型中定义的relationship_key
作为数组中的键:
$subcategory->save(
array(
'category' => $parent_category,
'zone' => $zone
)
);
请查看本页底部的文档和示例: http://datamapper.wanwizard.eu/pages/save.html