【问题标题】:Kohana ORM Relationships and Displaying InformationKohana ORM 关系和显示信息
【发布时间】:2012-05-18 05:26:26
【问题描述】:

我不知道如何处理。

假设我有 3 个模型,A、B 和 C。

模型A有很多C,模型B有很多C,C属于A和B。

我得到了所有的 B。

$getBs=ORM::factory('B')->find_all(); 

我显示 A、B、C。

foreach($getBs as $getB)
{
    echo $getB->b_category_title;
    foreach($getB->C->find_all() as $getC)
    {
        echo $getC->c_title;
        echo $getA->a_author; //Problem part
    }
}

在显示 Model C 的信息时,我不知道如何访问 Model A 并将其连接到 Model C。

编辑

为了获得工作代码,我将模型 A - C 更改为模型一 - 三。

使用 _load_with 的 biakaveron 示例,我收到以下错误:

Database_Exception [ 1054 ]: Unknown column 'three.id_c' in 'on clause' [ SELECT `ones`.`a_id` AS `ones:a_id`, `ones`.`a_author` AS `ones:a_author`, `three`.* FROM `threes` AS `three` JOIN `twos_threes` ON (`twos_threes`.`id_c` = `three`.`c_id`) LEFT JOIN `ones` AS `ones` ON (`ones`.`a_id` = `three`.`id_c`) WHERE `twos_threes`.`id_b` = '1' ]

型号:

class Model_One extends ORM {

protected $_primary_key = 'a_id';

protected $_has_many = array(
    'threes'=> array(
        'model' => 'three',                
        'through' => 'ones_threes',   
        'far_key' => 'id_c',       
        'foreign_key' => 'id_a'   
        ),
    );
}

class Model_Two extends ORM {

protected $_primary_key = 'b_id';

protected $_has_many = array(
    'threes'=> array(
        'model' => 'three',                
        'through' => 'twos_threes',   
        'far_key' => 'id_c',       
        'foreign_key' => 'id_b'   
        ),
    );
}

class Model_Three extends ORM {

protected $_primary_key = 'c_id';

protected $_belongs_to = array(
    'ones'=> array(
        'model' => 'one',                
        'through' => 'ones_threes',    
        'far_key' => 'id_a',       
        'foreign_key' => 'id_c'   
        ),

'twos'=> array(
        'model' => 'two',                
        'through' => 'twos_threes',    
        'far_key' => 'id_b',       
        'foreign_key' => 'id_c'   
        ),
);

protected $_load_with = array('ones');
}

为什么要找three.id_c?

【问题讨论】:

    标签: orm kohana


    【解决方案1】:

    C 属于 A 和 B。

    foreach($getBs as $getB)
    {
        echo $getB->b_category_title;
        foreach($getB->C->find_all() as $getC)
        {
            echo $getC->c_title;
            echo $getC->A->a_author; 
        }
    }
    

    PS。只是一个注释。您可以使用 $_load_with 属性加载 C 和 A 对象:

    class Model_C extends ORM {
        // ...
        protected $_load_with = array('A');
        // ...
    }
    

    【讨论】:

    • 只是好奇_load_with 属性是如何工作的?假设表 C 通过列“a_id”与表 A 有关系。 Kohana 如何匹配这一切?表名和列名是否需要特殊格式?
    • $_load_with 仅包含一个关系别名,在$_belongs_to 属性中进行了完整描述。与加载模型前调用->with('A') 相同。
    • 我在使用 _load_with 属性时遇到错误。我将错误添加到我的帖子中。
    • 为什么是'foreign_key' => 'id_c' ?我想应该是'foreign_key' => 'c_id' 。检查您的外键名称。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 2011-03-24
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多