使用Yii的Cdbcriteria类如何才能获得完全连接(db是mysql)?我知道它可以通过左连接和右连接的联合实现.....但它的syntex我没有得到
答案 0 :(得分:-1)
$criteria = new CDbCriteria;
$criteria->with = array(
'posts' => array(
'joinType' => 'INNER JOIN',
'together' => true,
),
);
$models = User::model()->findAll($criteria);
foreach($models AS $model) {
echo $model->username;// gives you the username
foreach($model->posts AS $post) {
echo $post->title; // gives you the post title
}
}
// if it's about only one user:
$criteria = new CDbCriteria;
$criteria->addCondition('user_id', (int)$user_id);
$criteria->with = array(
'posts' => array('together' => true, 'joinType' => 'INNER JOIN'),
);
$model = User::model()->find($crieteria);
echo $model->username;
foreach ($model->posts AS $post) {
echo $post->title;
}
// also you can:
$model = User::model()->with('posts')->findByPk((int)$user_id);
echo $model->username;
foreach($model->posts AS $post) {
echo $post->title;
}
在上面的例子中,我们假设我们有一个用户表,它与posts表有一个很多关系,并且帖子关系是在Yii AR的relations()
方法中定义的。