代码之家  ›  专栏  ›  技术社区  ›  anthony

Kohana 2.3.4 ORM透视表查询

  •  1
  • anthony  · 技术社区  · 15 年前

    我正试图用Kohana的ORM查询一个透视表,我想知道是否有一个内置函数丢失了。目前我只为“类别”和“产品”表设置了两个模型。有一个数据透视表“Categories_Products”,但插入数据时不需要它的模型:

    $product = ORM::factory('product');
    $product->add(ORM::factory('category', $addCat));
    

    但是,如果不为它创建一个模型,我就无法找到如何查询它。“join_table”函数只返回透视表的名称(我起初认为它选择了表)。如果您可以在不使用模型的情况下将数据保存到透视表,那么在我看来,您应该能够以类似的方式检索数据。有什么想法吗?

    2 回复  |  直到 8 年前
        1
  •  0
  •   user945497    15 年前

    您可以访问您的类别,而无需像下面这样的任何显式请求:

    $product_object = ORM::factory('product', $your_product_id);
    
    foreach ($product->categores as category):
        //access category ORM object...
    endforeach;
    

    我想,当你第一次尝试访问你的产品时,Kohana会要求你的产品类别。

        2
  •  0
  •   anthony    14 年前

    这对我来说并不像预期的那样有效。我不断得到一个错误,该属性在模型中不存在。不过,这个脚本一直在工作。

                    $pivot = ORM::factory('category')->join_table('products'); //pivot table name between products and categories
                $productsTotal = ORM::factory('product')->join($pivot, $pivot . '.product_id', 'id')->where('category_id', $id)->find_all();