Kohana和ORM的关系has_many_through
16lz
2021-01-22
I have problem with Kohana 3.3 and ORM relationship has_many_through. I have two models
我对Kohana 3.3和ORM关系has_many_through有问题。我有两个型号
Model_Category
Model_Category
class Model_Category extends ORM {
protected $_table_name = 'category';
protected $_primary_key = 'category_id';
protected $_has_many = array(
'question' => array(
'model' => 'Question',
'through' => 'cat_question'
),
);
}
Model_Question
Model_Question
class Model_Question extends ORM {
protected $_table_name = 'question';
protected $_primary_key = 'question_id';
protected $_has_many = array(
'category' => array(
'model' => 'Category',
'through' => 'cat_question'
),
);
}
- And in table
cat_question
there are two columns,category_id, question_id
, - 在表cat_question中有两列,category_id,question_id,
- in table
question
:question_id, title, content, date
, - 在表的问题:question_id,标题,内容,日期,
- in
category
:category_id, name
- 在类别:category_id,名称
But it's not working preety good.. When i do it like that
但它不是很好的工作......当我这样做的时候
$orm = ORM::factory('Question')->find_all();
foreach($orm as $el) {
var_dump($el->category->name);
}
They shows me NULL, but I don't know why.
他们告诉我NULL,但我不知道为什么。
2 个解决方案
#1
0
I handle with this, Question model should be looks like that :
我处理这个,问题模型应该是这样的:
class Model_Question extends ORM {
protected $_table_name = 'question';
protected $_primary_key = 'question_id';
protected $_has_many = array(
'category' => array(
'model' => 'Category',
'through' => 'cat_question',
'far_key' => 'category_id',
'foreign_key' => 'question_id',
),
);
}
And Category models
和类别模型
class Model_Category extends ORM {
protected $_table_name = 'category';
protected $_primary_key = 'category_id';
protected $_has_many = array(
'question' => array(
'model' => 'Question',
'far_key' => 'question_id',
'through' => 'cat_question',
'foreign_key' => 'category_id'
),
);
}
And if we want all category with count question is in, do something like that:
如果我们想要所有带有计数问题的类别,请执行以下操作:
public function get_category_and_question() {
$orm = ORM::factory('Category');
$find = $orm->find_all();
foreach ($find as $element) {
$count = ORM::factory('Category', $element->category_id)->question->count_all();
$new_array[] = array(
'name' => $element->name,
'id' => $element->category_id,
'how_much' => $count
);
}
return $new_array;
}
I'm not pretty sure if that is really good solve but is not bad for me.
我不确定这是否真的很好解决,但对我来说并不坏。
更多相关文章
- 从模型到控制器并返回到模型的数据
- 装机建项目vs2017和mysql5.7下建项目用EF建实体模型的过程..
- 如何在产品和类别应用程序树中将1个表连接到(2个不同的表作为一个
- Netbeans6.1+JSF/VJSF/+JPA+MYSQL=酷炫快速开发模型
- Angular JS复选框 - 模型不默认为false
- three.js学习笔记 obj模型加载问题
- 如何在Sencha Touch中向模型添加自定义验证规则
- 在用户将'n'粘贴复制到文本字段后,如何更新视图模型?
- 如果外部应用程序更改了持久模型(服务器数据库),AngularJS可以自