yii关系数据库多表查询

两个表的model继承自CActiveRecord

class  User extends CActiveRecord
class  Post extends CActiveRecord

很明显,User和Post是一对多的关系

在两个Model中覆盖relations方法

//class Post
public function relations()
    {
        return array(
            'author'=>array(self::BELONGS_TO, 'User', 'id','select'=>'name')
        );
    }

// 格式为
// 'relationsName' => array("relationship", "关联表", "该表的外键")
// relationName 可以随意
// relationship 为
// self::BELONGS_TO
// self::HAS_MANY
// self::HAS_ONE
// self::MANY_MANY  四个常量

在postController中可以按照默认的,使用CActiveDataProvider获得$dataProvider,此时User表的数据已经默认关联上。

在输出的时候可以使用 author.name 来输出和此post关联的用户名

author是个对象,数据库中的字段即是它的属性。如果设定了select,那么返回的author对象只有指定的字段,反则拥有所有字段。

原文地址:https://www.cnblogs.com/leftice/p/3789562.html