Kohana ORM对象有4种关系类型:
belongs_to(多对一), has_many(一对多), has_many "through"(多对多)和 has_one(一对一).
他们的用法也比较简单,我用了两个表做测试,
article表:
CREATE TABLE IF NOT EXISTS `article` ( `aid` int(10) unsigned NOT NULL AUTO_INCREMENT, `cid` int(11) NOT NULL, `title` varchar(255) CHARACTER SET utf8 NOT NULL, `content` text CHARACTER SET utf8 NOT NULL, PRIMARY KEY (`aid`)) ENGINE=MyISAM;
category表:
CREATE TABLE IF NOT EXISTS `category` ( `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL DEFAULT '', PRIMARY KEY (`id`)) ENGINE=MyISAM
它们的关系很显然:
一个article 属于一个category (belongs_to)
一个category可以有多个article (has_many)
则在article模型中:
//多篇文章对应一个分类 protected $_belongs_to = array( 'category' => array( 'model' => 'category', 'foreign_key' => 'cid' ) );
在category模型中:
//一个分类拥有多篇文章 protected $_has_many = array( 'articles' => array( 'model' => 'article', 'foreign_key' => 'cid' ) );
在Controller中使用:
/** * @auth Mckee * @blog */ public function action_test() { //获取分类id为1的文章数量 echo ORM::factory('category', 1)->articles->count_all(); echo ORM::factory('article', 4)->category->name; }
更多详细内容请参考:
英文手册: