1

我对 ORM 很陌生,我有点理解这个定义。当我尝试实现关系时,混乱就开始了。

假设我有这两张桌子。

产品表:

+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| brand_id    | int(11)      | YES  |     | NULL    |                |
| name        | varchar(100) | YES  |     | NULL    |                |
| description | text         | YES  |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+

品牌名称表:

+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| name       | varchar(100) | YES  |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+

如何设置模型,$_has_many $_belongs_to以便当我这样做时$product1 = Model_Product::find('first'); 它还返回品牌名称,就像在 SQL 连接中一样。

或者我是不是走错了路。

这不必特定于fuelphp,我只想在这种情况下如何设置ORM。

4

2 回答 2

2

在fuelphp中,您可以使用ORM simpli在模型文件中定义关系:

型号/品牌.php

class Model_Brand extends Orm\Model {

   protected static $_has_many = array(
        'products' => array(
            'model_to' => 'Model_Product',
            'key_from' => 'id',
            'key_to' => 'brand_id',
            'cascade_save' => false,
            'cascade_delete' => true,
        )
    );
}

型号/product.php

class Model_Product extends Orm\Model {
    protected static $_belongs_to = array('brand');
}

当您执行时$brand = Model_Brand::find('first');,您可以访问产品列表$brand['products']

当您表演时$product = Model_Product::find('first');,您可以通过以下方式访问品牌$product['brand']

于 2011-09-09T07:23:59.697 回答
1

一个有点像 Rails 的例子是:

class Brand
  has_many :products
end

class Product
  belongs_to :brand
end

product = Product.first
product.brand
=> <#Brand...>
brand = Brand.first
brand.products
=> [<#Product...>, <#Product...>]

这无论如何都不是完整的代码,但希望你能明白这一点。

于 2011-07-25T18:00:16.257 回答