dongyi7966 2011-07-25 14:15
浏览 47
已采纳

有人可以解释当前Web框架中使用的ORM吗?

I'm very new to ORM and I kind of understand the definition. Confusion starts when I try to implement relations.

Suppose I have these two tables.

Products table:

+-------------+--------------+------+-----+---------+----------------+
| 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    |                |
+-------------+--------------+------+-----+---------+----------------+

Brand names table:

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

How do I set up the models with $_has_many $_belongs_to so that when I do $product1 = Model_Product::find('first'); It also returns the name of the brand, like in SQL joins.

Or am I going about this the wrong way.

This doesn't have to be specific to fuelphp, I just want how to setup ORMs in this case.

  • 写回答

2条回答 默认 最新

  • douhuan1648 2011-09-09 07:23
    关注

    In fuelphp you can use ORM simpli define the relation in the model file:

    model/brand.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,
            )
        );
    }
    

    model/product.php

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

    When you'll perform $brand = Model_Brand::find('first'); you can access list of products with $brand['products']

    When you'll perform $product = Model_Product::find('first'); you can access the brand with $product['brand']

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?