ORM::联表查询

按顺序来一步一步走:

第一先建立好数据库:我的数据库是mysql数据库,数据库共分为以下几个表:

users  用户表(刚开始的时候我用的是user表名,由于kohana有喜欢建立model时在后面加复数的习惯,但是估计 user这个名字已经被占用了,指定$_table_name="user"也不行)

posts 帖子

数据库导出代码如下:

-- phpMyAdmin SQL Dump
-- version 3.4.10.1deb1
-- http://www.phpmyadmin.net
--
-- 主机: localhost
-- 生成日期: 2014 年 05 月 16 日 12:28
-- 服务器版本: 5.5.37
-- PHP 版本: 5.3.10-1ubuntu3.11

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

--
-- 数据库: `esystem`
--

-- --------------------------------------------------------

--
-- 表的结构 `posts`
--

CREATE TABLE IF NOT EXISTS `posts` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(10) unsigned NOT NULL,
  `label_id` int(10) unsigned NOT NULL,
  `title` varchar(255) NOT NULL,
  `content` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=20 ;

--
-- 转存表中的数据 `posts`
--

INSERT INTO `posts` (`id`, `user_id`, `label_id`, `title`, `content`) VALUES
(1, 1, 1, 'this is first title', 'this is first content'),
(2, 1, 2, 'this is 2nd title', 'this is 2nd content'),
(19, 4, 1, 'asdfas', 'dasb');

-- --------------------------------------------------------

--
-- 表的结构 `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `u_name` char(20) DEFAULT NULL,
  `password` char(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=gbk AUTO_INCREMENT=4 ;

--
-- 转存表中的数据 `users`
--

INSERT INTO `users` (`id`, `u_name`, `password`) VALUES
(1, 'root', '123456'),
(2, '小王', '123456'),
(3, 'lzj', '1111');
View Code

 用户与帖子是一对多的关系,所有 用户 has many 帖子:

故:

<?php
class Model_User extends ORM {
    protected $_has_many = array (
            'Post' => array (
                    'model' => 'Post',
                    'foreign_key' => 'id' 
            ) ,
        );
}
View Code
<?php
class Model_Post extends ORM {
    protected $_belongs_to = array (
            'User' => array (
                    'model' => 'User',
                    'foreign_key' => 'user_id' 
            ),
            'Lable' => array (
                    'model' => 'Lable',
                    'foreign_key' => 'label_id' 
            ) 
    );
    protected $_has_many = array (
            'Comment' => array (
                    'model' => 'Comment',
                    'foreign_key' => 'id' 
            )
    );
}
View Code

用法:

$post=ORM::factory("Post")->with("User")->find_all();

该用法是利用 Post下的$_belongs_to属性寻找User对象。

如何实现 select id as pid from posts;

ORM::factory("Post")->select(array('id','pid'))->find_all();

ERROR:

经查证 : ORM 下的$_has_many中foreign_key的值应该是相关联表的字段名称。

       ORM 下的 $_belongs_to中的foreign_key的值应该是相关联表对应自身表字段名称。

     举个例子:

      一个帖子 有 多个评论发言

      一个帖子  -------------他没有外键。他的id被人拿去做外键了。

      评论的外键 就是 post_id了。 所以他们两表关联起来   foreign_key应该是相同的。

原文地址:https://www.cnblogs.com/canbefree/p/3731952.html