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条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?