0

我对 Kohana 3.3 和 ORM 关系 has_many_through 有疑问。我有两个模型

型号_类别

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'
        ),
    );

}

模型_问题

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,,
  • 在表中questionquestion_id, title, content, date
  • categorycategory_id, name

但这不是很好。当我这样做时

$orm = ORM::factory('Question')->find_all();
foreach($orm as $el) {
    var_dump($el->category->name);
}

他们告诉我NULL,但我不知道为什么。

4

2 回答 2

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;
    }

我不太确定这是否真的很好解决,但对我来说还不错。

于 2013-09-17T13:31:12.673 回答
0

问题是,has_many_through 意味着多对多。所以一个类别包含多个问题,反之亦然。现在,如果您遵循 Kohana 的标准,您的数据库名称将是categories, questions, categories_questions并且名称将是复数,因此可以通过categoriesor访问questions

但你没有,要工作你的代码需要如下所示

$orm = ORM::factory('Question')->find_all();
foreach($orm as $el)
{
    $categories = $el->category->find_all();
    foreach ($categories as $category)
    {
        var_dump($category->name);
    }
}
于 2013-09-17T14:00:50.823 回答