Related
I was trying to make a blog with YII2, my framework is confusing to call data from database.
For example when I call "username" from "user" table,
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'user.fullname', --->> Yii2 is thinking that this is a category and not a user table
'title',
'description',
'content:html',
'count_view',
'status',
'created_at',
],
]) ?>
I am getting this error: -->> unknown property: app\models\Category::fullname
please could you help me to solve this issue, where I did make a mistake?
and here is my post model contains:
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "post".
*
* #property integer $id
* #property integer $user_id
* #property string $title
* #property string $description
* #property string $content
* #property integer $count_view
* #property string $status
* #property string $created_at
*
* #property User $user
* #property TagAssign[] $tagAssigns
*/
class Post extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'post';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['user_id', 'count_view','category_id'], 'integer'],
[['content', 'status'], 'string'],
[['created_at'], 'safe'],
[['count_view'], 'default','value'=>0],
[['user_id'], 'default','value'=>Yii::$app->user->id],
[['title', 'description'], 'string', 'max' => 255],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'user_id' => 'User ID',
'title' => 'Title',
'description' => 'Description',
'content' => 'Content',
'category' => 'Category',
'count_view' => 'Count View',
'status' => 'Status',
'created_at' => 'Created At',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(Category::className(), ['id' => 'user_id']);
}
public function getCategory()
{
return $this->hasOne(User::className(), ['id' => 'category_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getTagAssigns()
{
return $this->hasMany(TagAssign::className(), ['post_id' => 'id']);
}
}
and here user Model:
<?php
namespace app\models;
use Yii;
use yii\web\IdentityInterface;
/**
* This is the model class for table "user".
*
* #property integer $id
* #property string $username
* #property string $password
* #property string $fullname
* #property string $status
* #property string $role
* #property string $created_At
*
* #property Post[] $posts
*/
class User extends \yii\db\ActiveRecord implements IdentityInterface
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'user';
}
public $current_password;
public $new_password;
public $confirm_password;
public $authKey;
/**
* #inheritdoc
*/
public function rules()
{
return [
[['status', 'role'], 'string'],
[['created_At'], 'safe'],
[['username', 'password', 'fullname'], 'string', 'max' => 45],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => 'username',
'password' => 'password',
'fullname' => 'fullname',
'status' => 'Status',
'role' => 'Role',
'created_At' => 'Created At',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getPosts()
{
return $this->hasMany(Post::className(), ['user_id' => 'id']);
}
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;
}
public static function findByUsername($username)
{
return static::findOne(['username'=>$username]);
}
public function validatePassword($password)
{
if(Yii::$app->security->validatePassword($password,$this->password))
{
return true;
} else {
return false;
}
}
}
Change to this in Post model.
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'category_id']);
}
public function getCategory()
{
return $this->hasOne(Category::className(), ['id' => 'user_id']);
}
I'm new in StackOverflow and also new using the framework Yii 2, and I need to get session data and put in a create and update form using the _form.php from a view called Planficacion, but when I try to use this line of code in the form:
<?= $form->field($model, 'rutProfesor')->dropDownList(ArrayHelper::getvalue(Yii::$app->user->identity->rutProfesor,'nombreProfesor')) ?>
Return this error: PHP Warning – yii\base\ErrorException. Invalid argument supplied for foreach()
I need to get the value of 'nombreProfesor' from a model called Profesor, and the relation of both Planificacion and Profesor is 'rutProfesor' and I want to show in the dropDownList only the 'nombreProfesor' of the actual session.
There are the codes from:
Profesor Model (Profesor.php)
<?php
namespace common\models;
use Yii;
class Profesor extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'profesor';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['rutProfesor'], 'required'],
[['nombreProfesor', 'apellidoProfesor', 'escuelaProfesor'], 'string', 'max' => 45],
[['rutProfesor', 'claveProfesor'], 'string', 'max' => 15],
[['rol'], 'string', 'max' => 2],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'nombreProfesor' => 'Nombre Profesor',
'apellidoProfesor' => 'Apellido Profesor',
'escuelaProfesor' => 'Escuela',
'rutProfesor' => 'Rut',
'claveProfesor' => 'Clave Profesor',
'rol' => 'Rol',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getPlanificacions()
{
return $this->hasMany(Planificacion::className(), ['rutProfesor' => 'rutProfesor']);
}
}
Planificacion Model (planificacion.php)
<?php
namespace common\models;
use Yii;
class Planificacion extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'planificacion';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['fecha', 'fechaRevision', 'fechaPlanificacion'], 'safe'],
[['objetivosPlanificacion', 'actividad1', 'actividad2', 'actividad3', 'actividad4', 'obsActividad1', 'obsActividad2', 'obsActividad3', 'obsActividad4', 'contenidoActividad1', 'contenidoActividad2', 'contenidoActividad3', 'contenidoActividad4'], 'string'],
[['rutProfesor'], 'string', 'max' => 15],
[['nombreSesion', 'recursosUtilizadosPlanificacion', 'estadoActividad1', 'estadoActividad2', 'estadoActividad3', 'estadoActividad4', 'evalActividad1', 'evalActividad2', 'evalActividad3', 'evalActividad4', 'nombreSupervisor', 'asistencia'], 'string', 'max' => 255],
[['estado', 'rutSupervisor'], 'string', 'max' => 30],
[['rutProfesor'], 'exist', 'skipOnError' => true, 'targetClass' => Profesor::className(), 'targetAttribute' => ['rutProfesor' => 'rutProfesor']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'idPlanificacion' => 'Id Planificacion',
'rutProfesor' => 'Nombre Profesor',
'fecha' => 'Fecha',
'nombreSesion' => 'Nombre Sesion',
'objetivosPlanificacion' => 'Objetivos Planificacion',
'recursosUtilizadosPlanificacion' => 'Recursos Utilizados Planificacion',
'actividad1' => 'Actividad1',
'actividad2' => 'Actividad2',
'actividad3' => 'Actividad3',
'actividad4' => 'Actividad4',
'estadoActividad1' => 'Estado Actividad1',
'estadoActividad2' => 'Estado Actividad2',
'estadoActividad3' => 'Estado Actividad3',
'estadoActividad4' => 'Estado Actividad4',
'obsActividad1' => 'Obs Actividad1',
'obsActividad2' => 'Obs Actividad2',
'obsActividad3' => 'Obs Actividad3',
'obsActividad4' => 'Obs Actividad4',
'contenidoActividad1' => 'Contenido Actividad1',
'contenidoActividad2' => 'Contenido Actividad2',
'contenidoActividad3' => 'Contenido Actividad3',
'contenidoActividad4' => 'Contenido Actividad4',
'evalActividad1' => 'Eval Actividad1',
'evalActividad2' => 'Eval Actividad2',
'evalActividad3' => 'Eval Actividad3',
'evalActividad4' => 'Eval Actividad4',
'estado' => 'Estado',
'fechaRevision' => 'Fecha Revision',
'rutSupervisor' => 'Rut Supervisor',
'fechaPlanificacion' => 'Fecha Planificacion',
'nombreSupervisor' => 'Nombre Supervisor',
'asistencia' => 'Asistencia',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getAsistencias()
{
return $this->hasMany(Asistencia::className(), ['idPlanificacion' => 'idPlanificacion']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getRutProfesor0()
{
return $this->hasOne(Profesor::className(), ['rutProfesor' => 'rutProfesor']);
}
}
User Model (User.php)
<?php
namespace common\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
const ROLE_SUPERVISOR = 1;
const ROL_PROFESOR = 2;
public $authKey;
/** #inheritdoc
/**
*/
public static function tableName()
{
return 'profesor';
}
/**
* #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($rutProfesor)
{
return static::findOne(['rutProfesor' => $rutProfesor]);
}
/**
* #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($rutProfesor)
{
return static::findOne(['rutProfesor' => $rutProfesor]);
}
/**
* 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->authKey;
}
/**
* #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($claveProfesor)
{
return $this->claveProfesor === $claveProfesor;
}
/**
* 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 function isUserSimple($rutProfesor)
{
if(static::findOne(['rutProfesor' => $rutProfesor, 'rol' => 2]))
{
return true;
} else {
return false;
}
}
public function isUserAdmin($rutProfesor)
{
if(static::findOne(['rutProfesor' => $rutProfesor, 'rol' => 1]))
{
return true;
} else {
return false;
}
}
}
Planificacion Controller (planificacionController.php)
<?php
namespace frontend\controllers;
use Yii;
use common\models\Planificacion;
use common\models\PlanificacionSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* PlanificacionController implements the CRUD actions for Planificacion model.
*/
class PlanificacionController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Planificacion models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new PlanificacionSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Planificacion model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Planificacion model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Planificacion();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->idPlanificacion]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Planificacion 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->save()) {
return $this->redirect(['view', 'id' => $model->idPlanificacion]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Planificacion 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 Planificacion model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Planificacion the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Planificacion::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
First, why you getting the error, is because ArrayHelper::getValue() require an array as first parameter, as it's purpose is to
Retrieves the value of an array element or object property with the
given key or property name.
And Yii::$app->user->identity->rutProfesor wouldn't yield an array, no, it would yield an single string, which is current rutProfessor in the session.
Then, on how you create the dropDownList you wanted, i suggest using an ArrayHelper::map() which is more straightfoward.
<?= $form->field($model, 'rutProfesor')->dropDownList(ArrayHelper::map(Profesor::find()->where([
'rutProfesor' => Yii::$app->user->identity->rutProfesor
])->all(), 'rutProfesor', 'nombreProfesor'); ?>
I beleive that code will do you good.
Happy coding. :)
I am newbie in YII framework. I have installed correctly and created a Test Controller & Test Model using GII extension of YII. I have created a method in Model and want to access in Controller but unable to access.
Test controller
<?php
namespace app\controllers\api;
use Yii;
use app\models\api\Test;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
class TestController extends \yii\web\Controller
{
public $modelClass = 'app\models\api\Test';
private $model;
public function filters(){
return array(
'accessControl', // perform access control for CRUD operations
array(
'RestfullYii.filters.ERestFilter +
REST.GET, REST.PUT, REST.POST, REST.DELETE, REST.OPTIONS'
),
);
}
public function actions(){
return array(
'REST.'=>'RestfullYii.actions.ERestActionProvider',
);
}
public function accessRules(){
return array(
array('allow', 'actions'=>array('REST.GET', 'REST.PUT', 'REST.POST', 'REST.DELETE', 'REST.OPTIONS'),
'users'=>array('*'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
protected function loadModel( $id = null )
{
if($this->model===null)
{
if($id!==null)
$this->model=TestModel::model()->findByPk($id);
}
return $this->model;
}
public function actionIndex()
{
//return $this->render('index');
//$array = $modelClass::model()->listUserData();
//$array = Yii::app()->model()->listUserData();
//$array = $modelClass->listUserData();
// echo TestModel()->listUserData();
print "<pre>";print_r($this->model->listUserData());
exit;
}
}
Test Model
<?php
namespace app\models\api;
use Yii;
/**
* This is the model class for table "users".
*
* #property integer $id
* #property string $username
* #property string $password
* #property string $email
* #property string $activkey
* #property integer $createtime
* #property integer $lastvisit
* #property integer $superuser
* #property integer $status
*/
class Test extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'users';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['username', 'password', 'email'], 'required'],
[['createtime', 'lastvisit', 'superuser', 'status'], 'integer'],
[['username'], 'string', 'max' => 50],
[['password', 'email', 'activkey'], 'string', 'max' => 128],
[['username'], 'unique'],
[['email'], 'unique'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => 'Username',
'password' => 'Password',
'email' => 'Email',
'activkey' => 'Activkey',
'createtime' => 'Createtime',
'lastvisit' => 'Lastvisit',
'superuser' => 'Superuser',
'status' => 'Status',
];
}
public static function listUserData(){
$UserData = Test::model()->findAll('status = "0"');
return $UserData;
}
}
i tried to search on forum but not able to resolve, please can you help me to resolve ?
Thanks in advance.
In the controller.
use pathtotestmodel/Test
public function actionIndex()
{
$model = new Test();
$userdata = $model->listUserData();
}
OR
public function actionIndex()
{
$userdata = Test::listUserData();
}
Its simple create a instance of Model and then call the required function
like
public function actionIndex()
{
$model = new Test();
print "<pre>";print_r($model->listUserData());
exit;
}
Try this
public static function listUserData(){
$UserData = Test::findAll(['status' =>0]);//in Yii2
//$UserData = Test::model()->findByAttributes(array( 'status' => 0 )); in yii 1.1
return $UserData;
}
I have user, role tables and a junction table role_user for many to many relationship between these tables.
Timestamp and Blameable behaviours works fine for user and role tables but i want to add these behaviours to my junction table too.
My models are;
User.php
namespace backend\models;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "user".
*
* #property integer $id
* #property string $username
* #property string $auth_key
* #property string $password_hash
* #property string $password_reset_token
* #property string $email
* #property integer $status
* #property integer $created_at
* #property integer $updated_at
* #property string $name
* #property string $surname
* #property integer $role_id
*/
class User extends ActiveRecord {
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
public static function getStates() {
return ArrayHelper::map([
['id' => User::STATUS_ACTIVE, 'name' => 'Active'],
['id' => User::STATUS_DELETED, 'name' => 'Deleted'],
], 'id', 'name');
}
/**
* #inheritdoc
*/
public function behaviors() {
return [
TimestampBehavior::className(),
BlameableBehavior::className()
];
}
/**
* #inheritdoc
*/
public static function tableName() {
return 'user';
}
/**
* #inheritdoc
*/
public function rules() {
return [
[['username', 'auth_key', 'password_hash', 'email'], 'required'],
[['status', 'created_at', 'updated_at', 'created_by', 'updated_by'], 'integer'],
[['username', 'password_hash', 'password_reset_token', 'email', 'name', 'surname'], 'string', 'max' => 255],
[['auth_key'], 'string', 'max' => 32],
[['email'], 'unique'],
[['password_reset_token'], 'unique'],
[['username'], 'unique']
];
}
/**
* #inheritdoc
*/
public function attributeLabels() {
return [
'id' => 'ID',
'username' => 'Username',
'auth_key' => 'Auth Key',
'password_hash' => 'Password Hash',
'password_reset_token' => 'Password Reset Token',
'email' => 'Email',
'status' => 'Status',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'created_by' => 'Created By',
'updated_by' => 'Updated By',
'name' => 'Name',
'surname' => 'Surname',
'roles' => 'Roles',
];
}
/**
* #return ActiveQuery
*/
public function getRoles() {
return $this->hasMany(Role::className(), ['id' => 'role_id'])
->viaTable(RoleUser::tableName(), ['user_id' => 'id']);
}
}
Role.php
namespace backend\models;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
/**
* This is the model class for table "role".
*
* #property integer $id
* #property string $name
* #property integer $status
* #property string $created_at
* #property string $updated_at
*
* #property User[] $users
*/
class Role extends ActiveRecord {
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
public static function getStates() {
return ArrayHelper::map([
['id' => Role::STATUS_ACTIVE, 'name' => 'Active'],
['id' => Role::STATUS_DELETED, 'name' => 'Deleted'],
], 'id', 'name');
}
/**
* #inheritdoc
*/
public function behaviors() {
return [
TimestampBehavior::className(),
BlameableBehavior::className()
];
}
/**
* #inheritdoc
*/
public static function tableName() {
return 'role';
}
/**
* #inheritdoc
*/
public function rules() {
return [
[['status', 'created_at', 'updated_at', 'created_by', 'updated_by'], 'integer'],
[['name'], 'string', 'max' => 255]
];
}
/**
* #inheritdoc
*/
public function attributeLabels() {
return [
'id' => 'ID',
'name' => 'Name',
'status' => 'Status',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'created_by' => 'Created By',
'updated_by' => 'Updated By',
];
}
/**
* #return ActiveQuery
*/
public function getUsers() {
return $this->hasMany(User::className(), ['role_id' => 'id']);
}
}
RoleUser.php
<?php
namespace backend\models;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
/**
* This is the model class for table "role_user".
*
* #property integer $id
* #property integer $user_id
* #property integer $role_id
*
* #property Role $role
* #property User $user
*/
class RoleUser extends ActiveRecord {
/**
* #inheritdoc
*/
public function behaviors() {
return [
TimestampBehavior::className(),
BlameableBehavior::className()
];
}
/**
* #inheritdoc
*/
public static function tableName() {
return 'role_user';
}
/**
* #inheritdoc
*/
public function rules() {
return [
[['user_id', 'role_id'], 'required'],
[['user_id', 'role_id', 'status', 'created_at', 'updated_at', 'created_by', 'updated_by'], 'integer'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels() {
return [
'id' => 'ID',
'user_id' => 'User ID',
'role_id' => 'Role ID',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'created_by' => 'Created By',
'updated_by' => 'Updated By',
];
}
/**
* #return ActiveQuery
*/
public function getRole() {
return $this->hasOne(Role::className(), ['id' => 'role_id']);
}
/**
* #return ActiveQuery
*/
public function getUser() {
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
}
While i am linking a role to user iam using link method of ActiveRecord:
$user->link('roles', Role::findOne($role_id));
Is there a better way to link these models with these behaviours or should i do the linking via creating an instance from RoleUser model?
Thanks in advance.
If you want Yii to work with your RoleUser class inside link method then you should define relation using via not viaTable.
Declare additional relation:
User.php
public function getRoleLinks()
{
return $this->hasMany(UserRole::className(), ['user_id' => 'id']);
}
And modify your user->role relation:
public function getRoles() {
return $this->hasMany(Role::className(), ['id' => 'role_id'])
->via('roleLinks');
}
If you are using viaTable then yii will directly insert new record into user_role without instantiating of UserRole class.
p.s. and vice versa if you want to call $role->link('users', $user)
I try to make login from DB.As I understand for this i just need to replace default model User. So i try it two times but in both cases Yii::$app->user->isGuest is true but must be false
LoginForm.php
<?php
namespace app\models;
use Yii;
use yii\base\Model;
class LoginForm 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'],
];
}
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
} else {
return false;
}
}
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username); //default
# $this->_user = Users::findByUsername($this->username);//my try 1
# $this->_user = Users2::findByUsername($this->username); // my trey 2
}
return $this->_user;
}
}
Users.php
<?php
namespace app\models;
use Yii;
class Users extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
/**
* #inheritdoc
*/
public $authKey;
public $accessToken;
public static function tableName()
{
return 'users';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['name', 'surname', 'login', 'password', 'email'], 'required'],
[['name', 'surname'], 'string', 'max' => 50],
[['login'], 'string', 'max' => 20],
[['password'], 'string', 'max' => 16],
[['email'], 'string', 'max' => 250]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'surname' => 'Surname',
'login' => 'Login',
'password' => 'Password',
'email' => 'Email',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getOrders()
{
return $this->hasMany(Orders::className(), ['user_id' => 'id']);
}
public static function findIdentity($id) {
$user = self::find()
->where([
"id" => $id
])
->one();
if (!count($user)) {
return null;
}
return new static($user);
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $userType = null) {
$user = self::find()
->where(["accessToken" => $token])
->one();
if (!count($user)) {
return null;
}
return new static($user);
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username) {
$user = self::find()
->where([
"login" => $username
])
->one();
if (!count($user)) {
return null;
}
return new static($user);
}
/**
* #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 $this->password === $password;
}
}
Users2.php
<?php
namespace app\models;
use Yii;
class Users2 extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
/**
* #inheritdoc
*/
public static function tableName()
{
return '2sers';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['id'], 'integer'],
[['authKey', 'accessToken', 'name', 'surname', 'login', 'password', 'email'], 'required'],
[['authKey', 'accessToken'], 'string'],
[['name', 'surname'], 'string', 'max' => 50],
[['login'], 'string', 'max' => 20],
[['password'], 'string', 'max' => 16],
[['email'], 'string', 'max' => 250]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'authKey' => 'Auth Key',
'accessToken' => 'Access Token',
'name' => 'Name',
'surname' => 'Surname',
'login' => 'Login',
'password' => 'Password',
'email' => 'Email',
];
}
public static function findIdentity($id) {
$user = self::find()
->where([
"id" => $id
])
->one();
if (!count($user)) {
return null;
}
return new static($user);
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $userType = null) {
$user = self::find()
->where(["accessToken" => $token])
->one();
if (!count($user)) {
return null;
}
return new static($user);
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username) {
$user = self::find()
->where([
"login" => $username
])
->one();
if (!count($user)) {
return null;
}
return new static($user);
}
/**
* #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 $this->password === $password;
}
}
In your config change
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
To
'user' => [
'identityClass' => 'app\models\Users',//or Users2
'enableAutoLogin' => true,
You should also implement \yii\web\IdentityInterface. This is how Yii knows to log you in using this class.
When this is properly done...
Yii::$app->user will be an instance of yii\web\User, while
Yii::$app->user->identity would be an instance of app\models\User2
... as it should be.
P.S.:
Also make sure to implement the necessary methods from the \yii\web\IdentityInterface in your model class, app\models\User2