如何在Yii2中通过关系使用另一个模型类的活动查询方法

时间:2015-05-31 01:27:09

标签: php yii2

我有以下模型

/**
 * @property integer $id
 * @property string $title
 */
class Book extends ActiveRecord {
    public static function find() {
        return new BookQuery(self::class);
    }
}

class BookQuery extends ActiveQuery {
    public function andWhereTitleLike($string) {
        return $this->andWhere(['like', 'title', $string]);
    }
}

/**
 * @property integer $id
 * @property integer $userId
 * @property integer $bookId
 * @property integer $addedTime
 */
class FavoriteBook extends ActiveRecord {
     public function getBook() {
        return $this->hasOne(Book::class, ['id' => 'bookId']);
     }
}

查询当前登录用户的收藏书如下

$dataProvider = new ActiveDataProvider([
    'query' => FavoriteBook::find()
                   ->andWhere(['userId' => Yii::$app->user->id])
]);

但是如何通过重复使用上面BookQuery中的方法来查询包含特定标题的用户的收藏书?

2 个答案:

答案 0 :(得分:0)

尝试" joinWith"喜欢以下方式

FavoriteBook::find()
->joinWith(Book)    
->andWhere(['userId' => Yii::$app->user->id])

为确保其正常工作,您可以获取所有数组,打印记录并确认如下。

$fav_book = FavoriteBook::find()
->joinWith(Book)    
->andWhere(['userId' => Yii::$app->user->id])
->asArray()->all();

var_dump($fav_book);

答案 1 :(得分:0)

得到了答案

$dataProvider = new ActiveDataProvider([
    'query' => FavoriteBook::find()
               ->joinWith([
                   'book' => function(BookQuery $query) use ($title) {
                      return $query->andWhereTitleLike($title);
                   }
               ])
               ->andWhere(['userId' => Yii::$app->user->id])
]);