/** * Include user vote status. * * @param $entity * @return \yii\base\Component * @throws \yii\base\InvalidConfigException */ public function withUserVote($entity) { $entityEncoded = $this->getModule()->encodeEntity($entity); $model = new $this->owner->modelClass(); $voteTable = Vote::tableName(); $this->initSelect($model); $joinCondition = ["{$entity}.entity" => $entityEncoded, "{$entity}.target_id" => new Expression("`{$model->tableSchema->name}`.`{$model->primaryKey()[0]}`")]; $this->owner->addGroupBy("`{$model->tableSchema->name}`.`{$model->tableSchema->primaryKey[0]}`"); if (Yii::$app->user->isGuest) { $joinCondition["{$entity}.user_ip"] = Yii::$app->request->userIP; $joinCondition["{$entity}.user_id"] = null; } else { $joinCondition["{$entity}.user_id"] = Yii::$app->user->id; } $this->owner->leftJoin("{$voteTable} {$entity}", $joinCondition)->addSelect([new Expression("`{$entity}`.`value` as `{$entity}UserValue`")]); return $this->owner; }
/** * Creates new vote entry and returns response data. * * @param string $entity * @param integer $targetId * @param integer $value * @return array */ protected function createVote($entity, $targetId, $value) { $vote = new Vote(); $vote->entity = $entity; $vote->target_id = $targetId; $vote->value = $value; if ($vote->save()) { return ['success' => true]; } else { return ['success' => false, 'errors' => $vote->errors]; } }