2013-08-05 52 views
0

我想在Kohana 3.3中使用内置的ORM设置一个产品对象。我希望它这样,当我打电话:Kohana 3.3 ORM _has_many _belongs_to

$p1 = ORM::factory('product') 
     ->where('product_type', '=', '1') 
     ->find_all(); 

它将创建这个结构的对象:

Model_Product Object 
(
    [_long_list_of_kohana_properties] => Array() 
    [_object:protected] => Array 
     (
      [id] => 2 
      [product_type] => 1 
      ... 
      [product_attributes] => Array (List of attributes) 
     ) 
) 

目前,它会产生这样的:

Model_Product Object 
(
    [_long_list_of_kohana_properties] => Array() 
    [_object:protected] => Array 
     (
      [id] => 2 
      [product_type] => 1 
      ... 
     ) 
) 

这是相关代码对象和_has_many/_belongs_to:

class Model_Product extends ORM 
{ 
    protected $_db = 'default'; 
    protected $_table_name = 'product'; 
    protected $_primary_key = 'id'; 

    protected $_table_columns = array(
     'id', 
     'product_type', 
     ... 
    ); 

    protected $_has_many = array(
     'product_attributes' => array(
      'model' => 'productAttributes', 
      'foreign_key' => 'product_id', 
      'far_key' => 'id', 
     ) 
    ); 
} 

class Model_ProductAttribute extends ORM 
{ 
    protected $_db = 'default'; 
    protected $_table_name = 'productAttributes'; 
    protected $_primary_key = 'id'; 

    protected $_table_columns = array(
     'id', 
     'product_id', 
     'attribute_name', 
     'attribute_value', 
    ); 

    protected $_belongs_to = array('product' => array(
      'model' => 'product', 
      'foreign_key' => 'product_id', 
      'far_key' => 'product_id', 
     ) 
    ); 
} 

我似乎无法获得foreign_key和far_key值的正确组合来完成这项工作......另外,我无法找到“far_key”目的的很好解释。如果有人可以解释外国vs远端可能解决这个问题,哈。

任何关于我可能会搞砸的建议?

预先感谢您。

回答

2

Foreign keythis对象上的关键。这包含关于关系的数据。

Far keyother对象的关键。这包含关于关系的数据。该关键字'很远'

has_many关系中,其他对象'属于'此对象。这些对象上有一个键,它指的是this。因此,far key应该是'product_id'并且外键对此关系没有影响。由于this对象上没有(也不可能)指向数千个属性对象的对象。因此:

class Model_Product extends ORM { 

    protected $_has_many = array(
     'product_attributes' => array(
     'model' => 'productAttributes', 
     'far_key' => 'product_id', 
    )); 
} 

belongs_to的关系。 this对象上有一个指向它的密钥parent(或其他)。因此,本地密钥(foreign_key)应该是product_idfar_key对此关系没有影响。由于没有(也不可能)在指向所有孩子的另一个对象上有一个键。因此:

class Model_ProductAttribute extends ORM { 

    protected $_belongs_to = array('product' => array(
     'model' => 'product', 
     'foreign_key' => 'product_id', 
     'far_key' => 'product_id', 
    )); 
} 

我希望这能回答你的问题。花了一段时间弄清楚了。