在網上查過了很多yii框架多表查詢的問題,但總沒有適合自己的,自己建了幾張表過來分析,把操作寫出來分享Yii框架多表查詢(一對一與多對一)和多表條件聯合查詢給大家:
查一對一或多對一(常使用到的就是文章和文章分類關系)
在yii數據庫模型中比如有一個Post.php文件
代碼如下:
class Post extends CActiveRecord{
/*
* 返回當前模型對象的靜態方法
* 重寫父類CActiveRecord對應的方法
*/
public static function model($className = __CLASS__) {
return parent::model($className);
}
/*
* 返回當前數據表的名字
* 重寫父類CActiveRecord對應的方法
*/
public function tableName() {
return ‘{{post}}’;
}
//關聯查詢
public function relations()
{
return array(
//Post與User的關系是BELONGS_TO(多對一)關系,這里的author_id是User中的author_id
//’select’=>’id,username’查出來的字段
‘author’=>array(self::BELONGS_TO, ‘User’, ‘author_id’,'select’=>’id,username’),
);
}
}
需要弄清楚的幾點:
- (1),VarName是指一個對像;
- (2),RelationType。一共有4種,分別為self::HAS_MANY, self::BELONGS_TO, self::MANY_MANY, self::HAS_ONE。
- (3),ClassName。即關聯的另一個../model/類名.php。
- (4),ForeignKey。誰是誰的外鍵?
- (5),附加條件
要是在操作器中使用,那么我們得這么寫:
public function actionIndex(){
$post=post::model();
$criteria = new CDbCriteria();
//加一個條件就是author_id=2的
//$criteria->condition =”author_id=2″;
//這個是按什么條件排序
//$criteria->order = ‘t.author_id ASC’;
$criteria->with = array ( ‘author’ );
$result =$post->findAll( $criteria );
print_r($result);
}
以上的例子使用原生態的sql語句是這樣么寫的:
SELECT * FROM wn_post as p left join wn_user as u ON u.id=p.author_id
多表條件聯合查詢
根據網上查到的文章及YII官網介紹,整了好長時間。配置好relations。在search函數中需要如下處理:
// 指明關聯表
$criteria->with = array('authorizationProducts');
// 設置查詢條件
if($this->ap_status != '-1')
{
// together設置為True時,關聯表的數據會一起加載。否則會報錯。
$criteria->together = TRUE;
$criteria->compare('authorizationProducts.ap_status', $this->ap_status);
}
設置$criteria->together這步很重要,不然總是會報SQL語法錯誤。