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 = Mod开发者_开发问答el_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.
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']
An example in a somewhat Rails-ish way would be:
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...>]
This isn't complete code by any means but hopefully you'll get the idea.
精彩评论