I have a tree in which I am displaying nodes and their child nodes. I want to hide the non admin options to a user whose not an admin. By default, the isAdmin is true. For checking user roles I have done the following.
<?=
TreeView::widget([
'query' => \common\models\MdcNode::find()->addOrderBy('root, lft'),
'headingOptions' => ['label' => 'Root'],
'rootOptions' => ['label'=>'<span class="text-primary">Root</span>'],
'topRootAsHeading' => true, // this will override the headingOptions
'fontAwesome' => true,
'isAdmin' => function(){
if (Yii::$app->user->identity->user_role == 1)
{
return true;
}
else
{
return false;
}
},
'iconEditSettings'=> [
'show' => 'list',
'listData' => [
'building' => 'Building',
'folder' => 'Floor',
'user' => 'Customer'
]
],
'softDelete' => true,
'cacheSettings' => ['enableCache' => true]
]);
?>
Now when I run my code. I am getting below error when I click on the node
Operation Disallowed
Invalid request signature detected during tree data manage action! Please refresh the page and retry.
OLD HASH:
785a3cf9cbb1a90e862b718ed8ae3289944280448ae801de49d686aa5f70e951common\models\MdcNodehidebtn-default/mdc/backend/web/treemanager/node/save/mdc/backend/web/mdcnode/index#kvtree/views/_formw0-nodeselnodenodes<div class="kv-node-message">No valid nodes are available for display. Use toolbar buttons to add nodes.</div>111111{"id":"w0-nodeform"}{"1":"","2":"","3":"","4":"","5":""}{"submit":"<i class=\"glyphicon glyphicon-floppy-disk\"></i>","reset":"<i class=\"glyphicon glyphicon-repeat\"></i>"}a:0:{}[]list{"":"<em>Default</em> ( <span class=\"text-warning kv-node-icon kv-icon-parent\"><i class=\"fa fa-folder-close kv-node-closed\"></i></span> / <span class=\"text-warning kv-node-icon kv-icon-parent\"><i class=\"fa fa-folder-open kv-node-opened\"></i></span> / <span class=\"text-info kv-node-icon kv-icon-child\"><i class=\"fa fa-file\"></i></span>)","building":"<span class=\"fa fa-building\"></span> Building","folder":"<span class=\"fa fa-folder\"></span> Floor","user":"<span class=\"fa fa-user\"></span> Customer"}{"depth":"","glue":" » ","activeCss":"kv-crumb-active","untitled":"Untitled"}
NEW HASH:
e3037c327c2ddec080a38ce50002f825a214352f833f2acfe972c3d7d0a2b9abcommon\models\MdcNodehidebtn-default/mdc/backend/web/treemanager/node/save/mdc/backend/web/mdcnode/index#kvtree/views/_formw0-nodeselnodenodes<div class="kv-node-message">No valid nodes are available for display. Use toolbar buttons to add nodes.</div>11111{"id":"w0-nodeform"}{"1":"","2":"","3":"","4":"","5":""}{"submit":"<i class=\"glyphicon glyphicon-floppy-disk\"></i>","reset":"<i class=\"glyphicon glyphicon-repeat\"></i>"}a:0:{}[]list{"":"<em>Default</em> ( <span class=\"text-warning kv-node-icon kv-icon-parent\"><i class=\"fa fa-folder-close kv-node-closed\"></i></span> / <span class=\"text-warning kv-node-icon kv-icon-parent\"><i class=\"fa fa-folder-open kv-node-opened\"></i></span> / <span class=\"text-info kv-node-icon kv-icon-child\"><i class=\"fa fa-file\"></i></span>)","building":"<span class=\"fa fa-building\"></span> Building","folder":"<span class=\"fa fa-folder\"></span> Floor","user":"<span class=\"fa fa-user\"></span> Customer"}{"depth":"","glue":" » ","activeCss":"kv-crumb-active","untitled":"Untitled"}
Update 1
Below is my user model
class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
/**
* #inheritdoc
*/
public static function tableName()
{
return '{{%user}}';
}
/**
* #inheritdoc
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
/**
* #inheritdoc
*/
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
];
}
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['auth_key' => $token]);
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
}
/**
* Finds user by password reset token
*
* #param string $token password reset token
* #return static|null
*/
public static function findByPasswordResetToken($token)
{
if (!static::isPasswordResetTokenValid($token)) {
return null;
}
return static::findOne([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
]);
}
/**
* Finds out if password reset token is valid
*
* #param string $token password reset token
* #return bool
*/
public static function isPasswordResetTokenValid($token)
{
if (empty($token)) {
return false;
}
$timestamp = (int) substr($token, strrpos($token, '_') + 1);
$expire = Yii::$app->params['user.passwordResetTokenExpire'];
return $timestamp + $expire >= time();
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->auth_key;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return bool if password provided is valid for current user
*/
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_hash);
}
/**
* Generates password hash from password and sets it to the model
*
* #param string $password
*/
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
/**
* Generates new password reset token
*/
public function generatePasswordResetToken()
{
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
}
/**
* Removes password reset token
*/
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
public static function toArrayList()
{
return ArrayHelper::map(self::find()->where(['user_role'=>2,'status'=>10])->all(),'id','username');
}
}
User Table Structure
RBAC Model
class Rbac extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'rbac';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['controller', 'action'], 'string', 'max' => 50],
[['roles'], 'string', 'max' => 255],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'controller' => 'Controller',
'action' => 'Action',
'roles' => 'Roles',
];
}
public static function allowAccess($c,$a){
$sql= /** #lang text */
"select count(*) as total from rbac where (controller='$c' and action='$a') and (roles = '' OR roles IS NULL OR FIND_IN_SET(". Yii::$app->user->identity->user_role . ",roles)<>0)";
$rbac = Yii::$app->db->createCommand($sql);
$r = $rbac->queryOne();
return $r['total'] > 0;
}
}
Related
These are my files:
config/web.php
'user' => [
'identityClass' => '\app\models\User',
'enableAutoLogin' => false,
],
SiteController.php
public function actionSignin()
{
$model = new SigninForm();
if(!Yii::$app->user->isGuest)
{
return $this->goHome();
}
if($model->load(Yii::$app->request->post()) and $model->validate())
{
$identity = User::findOne(['email' => $model->email])
Yii::$app->user->login($identity);
}
return $this->render('signin',compact('model'));
}
User.php
namespace app\models;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
class User extends ActiveRecord implements IdentityInterface
{
/* and all methods Identityinterface is here!*/
}
I'm getting an error that I'm not using IdentityInterface in my User.php model. Where is my mistake?
You need to define all the methods necessary for Implementing IdentityInterface
as given here, and 2 additional methods that would be used by the login method add them to your class first.
class User extends ActiveRecord implements IdentityInterface
{
public static function findIdentity($id)
{
return static::findOne($id);
}
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['access_token' => $token]);
}
public function getId()
{
return $this->id;
}
public function getAuthKey()
{
return $this->authKey;
}
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
foreach (self::$users as $user) {
if (strcasecmp($user['username'], $username) === 0) {
return new static($user);
}
}
return null;
}
/**
* Validates password
*
* #param string $password password to validate
* #return bool if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->password === $password;
}
}
Then you SigninForm should look like following
<?php
namespace app\models;
use Yii;
use yii\base\Model;
/**
* SigninForm is the model behind the login form.
*
* #property User|null $user This property is read-only.
*
*/
class SigninForm extends Model {
public $username;
public $password;
public $rememberMe = true;
private $_user = false;
/**
* #return array the validation rules.
*/
public function rules() {
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* #param string $attribute the attribute currently being validated
* #param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params) {
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
/**
* Logs in a user using the provided username and password.
* #return bool whether the user is logged in successfully
*/
public function login() {
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0));
}
return false;
}
/**
* Finds user by [[username]]
*
* #return User|null
*/
public function getUser() {
if ($this->_user === false) {
$this->_user = User::findOne($this->username);
}
return $this->_user;
}
}
Update your Signup action to the following
public function actionSignin()
{
$model = new SigninForm();
if(!Yii::$app->user->isGuest)
{
return $this->goHome();
}
if($model->load(Yii::$app->request->post()) && $model->login())
{
return $this->goBack();
}
return $this->render('signin',compact('model'));
}
And then add the following inside your config/web.php under components as it is shown in the following example:
'components'=>[
'user' => [
'identityClass' => 'app\models\User', // User must implement the IdentityInterface
'enableAutoLogin' => true,
// 'loginUrl' => ['user/login'],
// ...
]
]
You should look into documentation more thoroughly here is a good video tutorial that would guide you step by step to implement your login interface.
Hope it helps
I want to implement user login into yii2 basic app.everything works properly except, when I tries to access Yii::$app->user->isGuest on layout main page. it always returns true. whats going wrong here?, please help me
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
Yii::$app->user->isGuest; // i m getting this as false, which is correct, but after goBack(), I m getting it as true
return $this->goBack();
}
return $this->render('login', [
'model' => $model,
]);
}
Login Mehod from LoginForm.php
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}
Note : I am using custom theme, which rests outside the web folder and inside project/themes/ directory
** User Model is as follows**
<?php
namespace app\models;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use yii\web\NotFoundHttpException;
class User extends ActiveRecord implements IdentityInterface {
private $id;
private $authKey;
const STATUS_DELETED = '0';
const STATUS_ACTIVE = '10';
public static function tableName() {
return '{{%user}}';
}
/**
* #inheritdoc
*/
public function behaviors() {
return [
TimestampBehavior::className(),
];
}
/**
* #inheritdoc
*/
public function getId() {
return $this->id;
}
/**
* #inheritdoc
*/
public function getAuthKey() {
return $this->authKey;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey) {
return $this->authKey === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validatePassword($password) {
return Yii::$app->security->validatePassword($password, $this->password_hash);
}
public static function findByEmail($email) {
$user_type = ['U'];
return static::find()
->andWhere('email = :email', [':email' => $email])
->andFilterWhere(['in', 'user_type', $user_type])
->one();
}
public static function findIdentity($id) {
$user = static::find()->where(['id' => $id, 'status' => self::STATUS_ACTIVE,])->one();
if (empty($user->id)) {
\Yii::$app->session->destroy();
}
return $user;
}
public static function findIdentityByAccessToken($token, $type = null) {
$user = static::find()
->where([
'access_token' => $token,
'status' => self::STATUS_ACTIVE,
])
->one();
if (!empty($user)) {
return $user;
} else {
throw new NotFoundHttpException('Invalid access token.');
}
}
}
Remove the lines:
private $id;
private $authKey;
from User class.
You should not directly declare ActiveRecord attributes that come from database as stated in the Guide.
Note: The Active Record attributes are named after the associated table columns in a case-sensitive manner. Yii automatically defines an attribute in Active Record for every column of the associated table. You should NOT redeclare any of the attributes.
I'm trying to make password changing function, by making a form for user to type in, then it will be hashed and added to password_hash record. To prevent it being populated with previous password, I added 'value'=>'' to clear it out.
But I have a problem with this: if I leave the field blank like its default state, the password_hash field in database will be blank, too. How can I make an exception that if this field is blank, then it will automatically take the old value in database, and if it has data inputted, it will take that value instead?
<?= $form->field($model, 'password')->passwordInput(['value'=>'']) ?>
EDIT: This is my controller file:
<?php
namespace app\controllers;
use app\models\User;
use Yii;
use app\models\UserList;
use app\models\UserlistSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* UserlistController implements the CRUD actions for UserList model.
*/
class UserlistController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all UserList models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new UserlistSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single UserList model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
public function actionDomains($id)
{
return $this->render('domains', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new UserList model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new UserList();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing UserList model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) ) {
$model->password_hash=Yii::$app->getSecurity()->generatePasswordHash($model->password_hash);
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing UserList model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the UserList model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return UserList the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = UserList::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
if(!empty($_POST['UserList']['password']){
---
}
Try:
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) ) {
if(!empty($_POST['UserList']['password']){
$model->password_hash=Yii::$app->getSecurity()->generatePasswordHash($_POST['UserList']['password']);
}
$model->save();
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I used both namespace in this file backend/models/User.php
When I use namespace app\models; It shows Unable to find 'backend\models\User'.
If I use namespace backend\models; It shows Unable to find 'app\models\User'
<?php
//namespace app\models;
namespace backend\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
const ROLE_USER = 10;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'admin';
}
/**
* #inheritdoc
*/
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
/**
* #inheritdoc
*/
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
['role', 'default', 'value' => self::ROLE_USER],
['role', 'in', 'range' => [self::ROLE_USER]],
];
}
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
}
/**
* Finds user by password reset token
*
* #param string $token password reset token
* #return static|null
*/
public static function findByPasswordResetToken($token)
{
if (!static::isPasswordResetTokenValid($token)) {
return null;
}
return static::findOne([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
]);
}
/**
* Finds out if password reset token is valid
*
* #param string $token password reset token
* #return boolean
*/
public static function isPasswordResetTokenValid($token)
{
if (empty($token)) {
return false;
}
$expire = Yii::$app->params['user.passwordResetTokenExpire'];
$parts = explode('_', $token);
$timestamp = (int) end($parts);
return $timestamp + $expire >= time();
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->auth_key;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_hash);
}
/**
* Generates password hash from password and sets it to the model
*
* #param string $password
*/
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
/**
* Generates new password reset token
*/
public function generatePasswordResetToken()
{
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
}
/**
* Removes password reset token
*/
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
}
I think your problem is, that you have two different models and try to use them both in one namespace, but this won't work.
You can alias one namespace, so you can use both different models.
eg.:
<?php
namespace app\models;
// there exist a model "User"
// and you wanna use also the User model under common\models\
use common\models\User as CUser;
Another solution is to prefixing the namespace to the model like
<?php
namespace app\models;
$cuser = new \common\models\User();
see PHP Namespaces explained
I have a project where users must be connected with each others - like friends. So i decided to connect them by the table 'connect'. Looks like it's rights. But when i tried to search for a friend requests i got the error, described below.
Here is my model User:
<?php namespace common\models
use dektrium\user\models\User as BaseUser;
use Yii;
use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;
use dosamigos\taggable\Taggable;
use yii\db\ActiveQuery;
/**
* User model
*
* #inheritdoc
* #property string $search
* #property string $category
*
* #property ActiveQuery $requests
*/
class User extends BaseUser
{
#region Properties
public $category;
public $search;
const SCENARIO_CATEGORY = 'category';
const SCENARIO_SEARCH = 'search';
#endregion
#region Yii
/**
* #inheritdoc
*/
public static function tableName()
{
return '{{%user}}';
}
/**
* #inheritdoc
*/
public function rules()
{
return array_merge(parent::rules(), [
[['category'], 'safe', 'on' => self::SCENARIO_CATEGORY],
[['search'], 'safe', 'on' => self::SCENARIO_SEARCH],
]);
}
/**
* #inheritdoc
*/
function scenarios()
{
return array_merge(parent::scenarios(), [
self::SCENARIO_CATEGORY => ['category'],
self::SCENARIO_SEARCH => ['search']
]);
}
#endregion
#region Callbacks
function afterFind()
{
$this->category = implode(', ', ArrayHelper::map($this->getCategories()->asArray()->all(), 'id', 'name'));
parent::afterFind();
}
/**
* #inheritdoc
*/
public function behaviors()
{
return array_merge(parent::behaviors(), [
[
'class' => Taggable::className(),
'attribute' => 'category',
'relation' => 'categories',
]
]);
}
#endregion
#region Relations
/**
* #return \yii\db\ActiveQuery
*/
function getCategories()
{
return $this->hasMany(Category::className(), ['id' => 'category_id'])->viaTable('{{%category_user}}', ['user_id' => 'id']);
}
/**
* #return \yii\db\ActiveQuery
*/
function getRequests()
{
return $this->hasMany(User::className(), ['id' => 'user_two'])->viaTable(Connection::tableName(), ['user_one' => 'id']);
}
#endregion
#region Methods
function search($params)
{
$query = self::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
// if (!$this->validate()) {
// $query->where('0=1');
// return $dataProvider;
// }
$query->joinWith(['categories']);
$query->andFilterWhere(['like', 'category.name', $this->search]);
return $dataProvider;
}
function isConnected($user_id)
{
return Connection::isConnected(Yii::$app->user->id, $user_id);
}
function requestCount()
{
return Connection::requestCount(Yii::$app->user->id);
}
function requestPends()
{
$query = $this->getRequests();
$result = new ActiveDataProvider([
'query' => $query
]);
$query->joinWith(['requests']);
$query->from(User::tableName() . ' u1');
$query->where = "";
$query->andFilterWhere(['connection.status' => Connection::STATUS_PENDED]);
return $result;
}
#endregion
}
Here is my connection model:
namespace common\models;
use Yii;
use yii\data\ActiveDataProvider;
use yii\db\Query;
/**
* This is the model class for table "connection".
*
* #property integer $id
* #property integer $user_one
* #property integer $user_two
* #property integer $status
*
* #property User $userOne
* #property User $userTwo
*/
class Connection extends \yii\db\ActiveRecord
{
const STATUS_PENDED = 0;
const STATUS_ACCEPTED = 1;
const STATUS_DENIED = 2;
public static function primaryKey()
{
return array('id');
}
/**
* #inheritdoc
*/
public static function tableName()
{
return 'connection';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['user_one', 'user_two', 'status'], 'integer'],
[['user_one'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_one' => 'id']],
[['user_two'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_two' => 'id']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'user_one' => Yii::t('app', 'User One'),
'user_two' => Yii::t('app', 'User Two'),
'status' => Yii::t('app', 'Status'),
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUserOne()
{
return $this->hasOne(User::className(), ['id' => 'user_one']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUserTwo()
{
return $this->hasOne(User::className(), ['id' => 'user_two']);
}
function search($params)
{
$query = self::find();
$result = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
// if (!$this->validate()) {
// $query->where('0=1');
// return $result;
// }
return $result;
}
static function isConnected($user_one, $user_two)
{
return self::find()->where('(user_one=:one AND user_two=:two) OR ((user_one=:two AND user_two=:one))', [':one' => $user_one, ':two' => $user_two])->andFilterWhere(['status' => Connection::STATUS_ACCEPTED])->count();
}
static function requestCount($user_id)
{
return (int)self::find()->where(['user_two' => $user_id])->andFilterWhere(['status' => Connection::STATUS_PENDED])->count();
}
}
request view:
<div class="panel panel-default">
<div class="panel-body">
<?php
// if ($mdlUser->requestCount()) {
echo ListView::widget([
'dataProvider' => $mdlUser->requestPends(),
'itemView' => '_list',
]);
// }
?>
</div>
</div>
Controller:
function actionFriendRequest()
{
/** #var User $mdlUser */
$mdlUser = Helper::findModel('\common\models\User', Yii::$app->user->id);
return $this->render('request', [
'mdlUser' => $mdlUser
]);
}
But yii2 make query like
`SELECT `u1`.* FROM `user` `u1` LEFT JOIN `connection` ON `u1`.`id` = `connection`.`user_one` LEFT JOIN `user` ON `connection`.`user_two` = `user`.`id` WHERE ((`connection`.`status`=0)) AND (0=1) LIMIT 20`
Question: Where did the (0=1) came from???
Take a look at your expression:
$mdlUser = Helper::findModel('\common\models\User', Yii::$app->user->id);
Most likely your 0=1 comes from Helper class, findModel method, which you haven't shown here.
UPDATE:
There are two more places where 0=1 can come from: QueryBuilder.php line 1077 and line 1226, which is the way yii2 handles empty strings/arrays for LIKE and IN conditions.