0

我正在尝试使用内置的 ORM 在 Kohana 3.3 中设置产品对象。我想要这样当我打电话时:

    $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”目的的很好解释。如果有人可以解释可能解决这个问题的foreign vs far,哈。

关于我可能在哪里搞砸的任何建议?

先感谢您。

4

1 回答 1

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_id并且far_key对这种关系没有影响。因为在另一个对象上没有(也不可能)指向它所有子对象的键。因此:

class Model_ProductAttribute extends ORM {

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

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

于 2013-08-15T09:49:26.370 回答