首页 > 解决方案 > YII2 - 保存用户 ID 以便在其他页面上使用它

问题描述

我正在建立一个问卷调查网站。
在这个网站上,用户输入他的电子邮件以接收他的问卷调查结果。所以这个网站没有认证。

如何将用户的电子邮件存储到问卷的末尾?

这是我的User模型:

<?php

namespace common\models;

use Yii;
use \yii\db\ActiveRecord;
// use yii\web\IdentityInterface;

/**
 * This is the model class for table "user".
 *
 * @property int $id
 * @property string $email
 * @property string $name
 * @property string $family
 * @property string $major
 * @property string $univercity
 * @property int $education
 * @property int $gender
 * @property int $age
 * @property int $income
 * @property int $get_result
 * @property int $created_at
 */
class User extends ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'user';
    }

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            // TimestampBehavior::className(),
        ];
    }


    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['email', 'created_at'], 'required'],
            [['education', 'gender', 'age', 'income', 'get_result', 'created_at'], 'integer'],
            [['email', 'name', 'family', 'major', 'univercity'], 'string', 'max' => 255],
            [['email'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'email' => 'Email',
            'name' => 'Name',
            'family' => 'Family',
            'major' => 'Major',
            'univercity' => 'Univercity',
            'education' => 'Education',
            'gender' => 'Gender',
            'age' => 'Age',
            'income' => 'Income',
            'get_result' => 'Get Result',
            'created_at' => 'Created At',
        ];
    }
}

标签: phpyii2yii2-advanced-appyii2-modelyii2-user

解决方案


有很多方法可以实现这一点,这主要取决于你的逻辑。

最简单的方法之一是使用会话。

首先将电子邮件存储在会话中:

\Yii::$app->session->set('questionnaire-email', $usersEmail);

然后,当你想使用它时:

$email = \Yii::$app->session->get('questionnaire-email');

推荐阅读