繁体   English   中英

Kohana和ORM关系has_many_through

[英]Kohana and ORM relationship has_many_through

我对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,但我不知道为什么。

我处理这个问题模型应该是这样的:

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

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

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

但是您没有,要运行您的代码,需要如下所示

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM