@AlexSer

Как d yii2 работать с моделью USER?

Ребят я еще новичок и все еще вникаю. Появился такой вопрос. Сам фраемворк содержит способы регистрации и авторизации. Есть стандартная таблица user, созданная путем миграции. Идея такова
5a66101a0dd25251691964.jpeg
Надо поменять стандартный admin, который отображается при авторизации, в левом верхнем углу на ФИО пользователя.Жду рекомендации,ссылок на аналогичное или шаги решения.Всем спасибо!

код
model User:
<?php
namespace frontend\models;
use Yii;
/**
 * This is the model class for table "user".
 *
 * @property int $id
 * @property string $username
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property int $status
 * @property int $created_at
 * @property int $updated_at
 * @property int $medpersonal_id
 *
 * @property Medpersonal $medpersonal
 */
class User extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'auth_key', 'password_hash', 'email', 'created_at', 'updated_at'], 'required'],
            [['status', 'created_at', 'updated_at', 'medpersonal_id'], 'integer'],
            [['username', 'password_hash', 'password_reset_token', 'email'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            [['username'], 'unique'],
            [['email'], 'unique'],
            [['password_reset_token'], 'unique'],
            [['medpersonal_id'], 'unique'],
            [['medpersonal_id'], 'exist', 'skipOnError' => true, 'targetClass' => Medpersonal::className(), 'targetAttribute' => ['medpersonal_id' => 'id']],
        ];
    }

    /**
     * @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',
            'medpersonal_id' => 'Medpersonal ID',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMedpersonal()
    {
        return $this->hasOne(Medpersonal::className(), ['userID' => 'id']);
    }
}

Модель Personal

<?php

namespace frontend\models;

use Yii;


class Personal extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'personal';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['idd', 'combination'], 'integer'],
            [['combination'], 'required'],
            [['FIO', 'position', 'specialnost'], 'string', 'max' => 50],
            [['position'], 'exist', 'skipOnError' => true, 'targetClass' => Position::className(), 'targetAttribute' => ['position' => 'position']],
            [['idd'], 'exist', 'skipOnError' => true, 'targetClass' => DuobleSubLu::className(), 'targetAttribute' => ['idd' => 'id']],
            [['specialnost'], 'exist', 'skipOnError' => true, 'targetClass' => Specialnost::className(), 'targetAttribute' => ['specialnost' => 'specialnost']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'FIO' => 'Fio',
            'position' => 'Position',
            'specialnost' => 'Specialnost',
            'idd' => 'Idd',
            'combination' => 'Combination',
        ];
    }


    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'userID']);
    }
}
?>

Как заменить admin в панели меню, который отображается при авторизации на ФИО пользователя
вот код странички main.php
$menuItems_log[] = '<li>'
            . Html::beginForm(['/site/logout'], 'post')
            . Html::submitButton(
                'Выход (' . Yii::$app->user->identity->username.')',
                ['class' => 'logout']
            )
            . Html::endForm()
            . '</li>';
  • Вопрос задан
  • 2116 просмотров
Пригласить эксперта
Ответы на вопрос 2
slo_nik
@slo_nik Куратор тега Yii
Добрый вечер.
Используйте связь между таблицами.
Во второй модели создайте метод, который будет возвращать Ф.И.О. пользователя.

p.s.
У Вас есть две модели, User и Personal.
Первая используется для авторизации, вторая используется для дополнительных данных пользователя.
Есть две связи, в модели User на модель Personal, в модели Personal на модель User.
С этим разобрались.
Но связи не работают у Вас как надо, связь идёт через несуществующие атрибуты. Например, откуда Вы взяли userID? Ни в одной из предоставленных моделей нет такого атрибута.
Добавьте в модель Personal атрибут userID, тогда связь будет работать.
Вот так связь будет выглядеть в модели User
public function getPersonal()
{
   retun $this->hasOne(Personal::className(), ['userID' => 'id']);
}

Но в данном случае, я думаю, связь особо не нужна. После авторизации у Вас есть id авторизованного пользователя Yii::$app->user->identity->id. Вот через этот параметр можно получить данные определённого пользователя из модели Personal.
В модели Personal можно создать статический метод для получения данных пользователя
public static function getDataUser($id)
{
   $model = Personal::find()->where('id=:id', [':id' => $id])->one();
   return $model;
}

И получить Ф.И.О пользователя можно будет так.
$data = Personal::dataUser(Yii::$app->user->identity->id);
echo $data->fio;

p.s.s. Код не проверял, возможны ошибки, но идея, я думаю, понятна.
Ответ написан
@AlexSer Автор вопроса
model User:
<?php
namespace frontend\models;
use Yii;
/**
 * This is the model class for table "user".
 *
 * @property int $id
 * @property string $username
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property int $status
 * @property int $created_at
 * @property int $updated_at
 * @property int $medpersonal_id
 *
 * @property Medpersonal $medpersonal
 */
class User extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'auth_key', 'password_hash', 'email', 'created_at', 'updated_at'], 'required'],
            [['status', 'created_at', 'updated_at', 'medpersonal_id'], 'integer'],
            [['username', 'password_hash', 'password_reset_token', 'email'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            [['username'], 'unique'],
            [['email'], 'unique'],
            [['password_reset_token'], 'unique'],
            [['medpersonal_id'], 'unique'],
            [['medpersonal_id'], 'exist', 'skipOnError' => true, 'targetClass' => Medpersonal::className(), 'targetAttribute' => ['medpersonal_id' => 'id']],
        ];
    }

    /**
     * @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',
            'medpersonal_id' => 'Medpersonal ID',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMedpersonal()
    {
        return $this->hasOne(Medpersonal::className(), ['userID' => 'id']);
    }
}
Модель Personal

<?php

namespace frontend\models;

use Yii;


class Personal extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'personal';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['idd', 'combination'], 'integer'],
            [['combination'], 'required'],
            [['FIO', 'position', 'specialnost'], 'string', 'max' => 50],
            [['position'], 'exist', 'skipOnError' => true, 'targetClass' => Position::className(), 'targetAttribute' => ['position' => 'position']],
            [['idd'], 'exist', 'skipOnError' => true, 'targetClass' => DuobleSubLu::className(), 'targetAttribute' => ['idd' => 'id']],
            [['specialnost'], 'exist', 'skipOnError' => true, 'targetClass' => Specialnost::className(), 'targetAttribute' => ['specialnost' => 'specialnost']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'FIO' => 'Fio',
            'position' => 'Position',
            'specialnost' => 'Specialnost',
            'idd' => 'Idd',
            'combination' => 'Combination',
        ];
    }


    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'userID']);
    }
}
?>
Как заменить   admin в панели меню, который отображается  при авторизации на ФИО пользователя
вот код странички main.php
    $menuItems_log[] = '<li>'
            . Html::beginForm(['/site/logout'], 'post')
            . Html::submitButton(
                'Выход (' . Yii::$app->user->identity->username.')',
                ['class' => 'logout']
            )
            . Html::endForm()
            . '</li>';
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы