我对Kohana 3.3和ORM关系has_many_through有问题。我有两个型号
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
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'
),
);
}
cat_question
中有两列,category_id, question_id
,question
中的question_id, title, content, date
,category
:category_id, name
但它不是很好的工作......当我这样做时
$orm = ORM::factory('Question')->find_all();
foreach($orm as $el) {
var_dump($el->category->name);
}
他们告诉我NULL,但我不知道为什么。
答案 0 :(得分:0)
我处理这个, 问题模型应该是这样的:
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',
),
);
}
和类别模型
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'
),
);
}
如果我们想要所有带有计数问题的类别,请执行以下操作:
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;
}
我不确定这是否真的很好解决,但对我来说并不坏。
答案 1 :(得分:0)
问题是,has_many_through意味着多对多。因此,一个类别包含多个问题,反之亦然。现在,如果您遵循Kohana的标准,您的数据库名称将为categories, questions, categories_questions
,名称将为复数,因此可通过categories
或questions
访问。
但是你没有,为了你的代码需要看起来像下面的
$orm = ORM::factory('Question')->find_all();
foreach($orm as $el)
{
$categories = $el->category->find_all();
foreach ($categories as $category)
{
var_dump($category->name);
}
}