ActiveRecord

最后更新于:2022-04-01 11:17:48

## Active Record ### 列出全部Restaurant ~~~ $model = Restaurant::find()->orderBy('name')->all(); return $this->render('index', ['model' => $model]); ~~~ ### 按Reviews数量排序 ~~~ $query = Restaurant::find() ->select(['restaurant.*', 'COUNT(review.id) AS reviewsCount']) ->joinWith('reviews'); $model = $query->orderBy('reviewsCount DESC')->groupBy('restaurant.id')->all(); return $this->render('index', ['model' => $model]); ~~~ ### 计算Total Rating和Average Rating ~~~ public function getTotalRating() { $totalRating = 0; foreach ($this->reviews as $review) { $totalRating += $review->rating; } return $totalRating; } public function getAverageRating() { return $this->totalRating / count($this->reviews); } ~~~ ### 搜索 ~~~ public function actionIndex($search = null) { if ($search) { //$query->where("restaurant.name like :name",[':name' => '%'.$search.'%']); $query->where(['like', 'name', $search]); } } ~~~
';