Kohana ORM关系和显示信息

时间:2012-05-16 23:18:58

标签: orm kohana

我不知道如何处理这个问题。

假设我有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
    }
}

在显示模型C的信息时,我不知道如何访问和连接模型A到模型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?

1 个答案:

答案 0 :(得分:2)

  

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');
    // ...
}