搜索
查看: 1357|回复: 0

Yii多表联合查询操作详解

[复制链接]

4856

主题

4856

帖子

4861

积分

新手上路

Rank: 1

积分
4861
发表于 2018-2-11 12:10:13 | 显示全部楼层 |阅读模式

            本文针对Yii多表联查进行汇总描述,供大家参考,具体内容如下
1、多表联查实现方法
有两种方式一种使用DAO写SQL语句实现,这种实现理解起来相对轻松,只要保证SQL语句不写错就行了。缺点也很明显,比较零散,而且不符合YII的推荐框架,最重要的缺点在于容易写错。
还有一种便是下面要说的使用YII自带的CActiveRecord实现多表联查
2、 整体框架
我们需要找到一个用户的好友关系,用户的信息放在用户表中,用户之间的关系放在关系表中,而关系的内容则放在关系类型表中。明显的我们只需要以关系表为主表联查其他两个表即可。我主要从代码的角度,分析下实现的过程。
3、CActiveRecord
我们首先需要对3张表建立相应的model,下面是关系表的代码
SocialRelation.php
true),
      // The following rule is used by search().
      // Please remove those attributes that should not be searched.
      array('relation_id, relation_type_id, user_id, another_user_id', 'safe', 'on'=>'search'),
    );
  }

  /**
   * @return array relational rules.
   */
  public function relations()
  {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
      'relationType' => array(self::BELONGS_TO, 'SocialRelationType', 'relation_type_id'),
      'user' => array(self::BELONGS_TO, 'AccessUser', 'user_id'),
      'anotherUser' => array(self::BELONGS_TO, 'AccessUser', 'another_user_id'),
    );
  }

  /**
   * @return array customized attribute labels (name=>label)
   */
  public function attributeLabels()
  {
    return array(
      'relation_id' => 'Relation',
      'relation_type_id' => 'Relation Type',
      'relation_type_name' => 'Relation Name',
      'user_id' => 'User ID',
      'user_name' => 'User Name',
      'another_user_id' => 'Another User',
      'another_user_name' => 'Another User Name',
    );
  }

  /**
   * Retrieves a list of models based on the current search/filter conditions.
   * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
   */
  public function search()
  {
    // Warning: Please modify the following code to remove attributes that
    // should not be searched.

    $criteria=new CDbCriteria;

    $criteria->compare('relation_id',$this->relation_id);
    $criteria->compare('relation_type_id',$this->relation_type_id);
    $criteria->compare('user_id',$this->user_id);
    $criteria->compare('another_user_id',$this->another_user_id);
    $criteria->with=array(
      'relationType',
    );

    return new CActiveDataProvider($this, array(
      'criteria'=>$criteria,
    ));
  }
}
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

长春门户网站

长春门户网是网民了解长春的网络窗口,同是提供长春地区百姓生活分类供求信息的门户网站,同时提供长春网站建设、长春网站设计,我们将逐步的完善网站分类信息资源;

长春门户网二维码

联系我们

  • 工作时间:早上8:00 - 晚上5:30
  • 投稿联系:13624467185(微信同号)
  • 反馈邮箱:5053050@QQ.com
  • 公司地址:吉林省长春市亚泰大街与自由大路交汇五环国际大厦1408室

QQ|小黑屋|手机版|Archiver|cc! ( 吉ICP备2021009740号-8 )

Powered by Discuz! X3.4 © 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表