lz19881123 2011-12-26 10:11:59 4656次浏览 7条回复 0 0 0

现在有一个news(新闻表)news表结构

CREATE TABLE `news` (
   `news_id` int(11) NOT NULL AUTO_INCREMENT,
   `news_title` varchar(50) NOT NULL,
   `news_visable` tinyint(1) NOT NULL,
   `news_author` varchar(50) NOT NULL,
   `news_content` text NOT NULL,
   `news_jianjie` varchar(50) NOT NULL,
   `news_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
   `news_type` int(11) NOT NULL,
   `news_count` int(11) NOT NULL,
   PRIMARY KEY (`news_id`)
 ) ENGINE=MyISAM AUTO_INCREMENT=96 DEFAULT CHARSET=utf8 COMMENT='新闻表'[/code]一个pinglun(评论表)[code]
create table
CREATE TABLE `pinglun` (
   `pl_id` int(11) NOT NULL AUTO_INCREMENT,
   `pl_content` varchar(250) NOT NULL,
   `pl_time` datetime NOT NULL,
   `pl_int` int(11) NOT NULL COMMENT '评论int',
   PRIMARY KEY (`pl_id`)
 ) ENGINE=MyISAM AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COMMENT='评论表'

现在不知道这两个表关联查询如何写?表的关系是(news.news_id=pl.pl_int)

  • 回复于 2011-12-26 10:42 举报

    哪个表联合哪个表?

  • 回复于 2011-12-26 11:00 举报

    晕倒,你到底有没看问题啊?

  • 回复于 2011-12-26 11:04 举报

    我是在model里面写

    $post=News::model()->with(array('pingluns'=>array('condition'=>'pl_int='.$_GET['id'])))->findAll();
    

    news的model relations

    public function relations()
    {
        return array(
            'pingluns'=>array(self::BELONGS_TO, 'Pinglun', 'news_id'),
        );
    }
    

    pinglun的model relations

    public function relations()
    {
        return array(
            'news'=>array(self::HAS_MANY, 'News', 'pl_int'),
    
        );
    }
    

    不知道哪里有错?
    如何才可以达到这样的效果呢?
    $sql="select * from news join pinglun on news_id=pinglun.pl_int where pl_int =".$_GET['id'];

  • 回复于 2011-12-26 13:56 举报

    晕,你这问问题的态度。。没看问题我回答你干啥?
    你只说了联合,只给了联合关系,我怎么知道你是要从哪个表联合到哪个表去?

  • 回复于 2011-12-26 13:58 举报

    貌似你把关系弄错了。。news里的应该是HAS_MANY,而pinglun里的才是BELONGS_TO

  • 回复于 2011-12-26 14:00 举报

    楼上正解

  • 回复于 2011-12-26 14:22 举报

    在Yii中支持自定义查询方式,提供了CDbCriteria类,该类提供以下属性:
    select:要查询的字段列表,默认是”*”,
    distinct:是否在查询语句中使用distinct
    condition:查询条件,如:'age>31 AND team=1'
    params:查询参数,如:array(':name'=>'Dan', ':age'=>31)
    limit:最大返回记录条数,如果小于0表示不限制
    offset:返回记录的起始位置,如果小于0表示从开始查询
    order:排序方式,如:
    group:分组方式,如:'projectID, teamID'
    join:连接查询方式,如:'LEFT JOIN users ON users.id=authorID'
    having:分组条件,如:'SUM(revenue)<50000
    本人代码中的一个例子:

    $criteria=new CDbCriteria;
    $criteria->select='MessageId,Title,ToUserID,IsRead,PostDate,FromUserID';
    $criteria->condition='MessageList.FromUserID='.Yii::app()->user->id;
    $criteria->order='MessageId desc';
    
    $pages=new CPagination(messagelist::model()->count($criteria));
    $pages->pageSize=self::PAGE_SIZE;
    $pages->applyLimit($criteria);
    
    $models=messagelist::model()->with('userList')->findAll($criteria);
    
您需要登录后才可以回复。登录 | 立即注册