-1

使用 Yii 的 Cdbcriteria 类如何获得完全加入(db 是 mysql)?我知道它可以通过左连接和右连接的联合来实现.....但是我没有得到它的语法

4

1 回答 1

-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;
}

在上面的例子中,我们假设我们有一个用户表,它与帖子表有一个:多的关系,并且帖子关系是在relations()Yii AR 的方法中定义的。

于 2013-05-09T12:36:48.117 回答