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

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题