public function afterSave($insert, $changedAttributes) { \Yii::$app->db->createCommand()->delete(UserLists::tableName(), 'list_id = ' . (int) $this->id)->execute(); foreach ($this->users as $id) { //Write new values $model = new UserLists(); $model->list_id = $this->id; $model->user_id = $id; $model->save(); } }
/** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = Lists::find(); $query->select($this->tableName() . '.*, COUNT(' . UserLists::tableName() . '.user_id) AS users_count'); $query->leftJoin(UserLists::tableName(), UserLists::tableName() . '.list_id = ' . $this->tableName() . '.id'); $query->groupBy([$this->tableName() . '.id']); $dataProvider = new ActiveDataProvider(['query' => $query]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } $query->andFilterWhere(['id' => $this->id, 'DATE(last_sent)' => $this->last_sent, 'DATE(created)' => $this->created, 'DATE(modified)' => $this->modified]); $query->andFilterWhere(['like', 'name', $this->name]); $dataProvider->setSort(['attributes' => ['id', 'name', 'last_sent', 'created', 'modified', 'users_count' => ['asc' => ['users_count' => SORT_ASC], 'desc' => ['users_count' => SORT_DESC], 'label' => 'Parent Name', 'default' => SORT_ASC]]]); return $dataProvider; }
private function send($model) { $list_id = $model->list_id; $records = UserLists::find()->joinwith('user')->where(['=', 'list_id', $list_id])->andWhere(['=', 'blocked', 0])->asArray()->all(); $content = $this->renderPartial('layout', ['content' => $model->body]); $users = []; foreach ($records as $record) { $users[$record['user']['id']] = $record['user']['email']; } if ($model->send_as_copy) { $result = $this->sendMail(implode(', ', $users), $model->subject, $content); foreach ($users as $user_id => $user) { $this->saveResult($model->id, $user_id, $result); } } else { foreach ($users as $user_id => $user) { $result = $this->sendMail($user, $model->subject, $content); $this->saveResult($model->id, $user_id, $result); } } }