Php 科哈纳和ORM的关系经历了很多次

Php 科哈纳和ORM的关系经历了很多次,php,frameworks,kohana,kohana-orm,kohana-3.3,Php,Frameworks,Kohana,Kohana Orm,Kohana 3.3,我对Kohana3.3有问题,ORM的关系已经经历了很多次。我有两种型号 车型类别 class Model_Category extends ORM { protected $_table_name = 'category'; protected $_primary_key = 'category_id'; protected $_has_many = array( 'question' => array( 'model'

我对Kohana3.3有问题,ORM的关系已经经历了很多次。我有两种型号

车型类别

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\u question
    中有两列,
    category\u id,question\u id
  • 在表
    问题
    问题id、标题、内容、日期
  • 类别中
    类别id,名称
但是它不起作用。。当我这样做的时候

$orm = ORM::factory('Question')->find_all();
foreach($orm as $el) {
    var_dump($el->category->name);
}
他们显示我为空,但我不知道为什么。

我处理这个, 问题模型应如下所示:

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

我不太确定这是否真的是一个很好的解决方案,但对我来说并不坏。

问题是,这意味着多对多。因此,一个类别包含多个问题,反之亦然。现在,如果您遵循Kohana的标准,您的db名称将是
类别、问题、类别和问题
,并且名称将是复数,因此可以通过
类别
问题
访问

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

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