0 レビュー
0 回答
php-データをテーブルに挿入する方法、保存する前に作成ユーザーを作成し、テーブルプライム(yii2)にidユーザーを使用しますか?
私には、user_id外部キーテーブルの学生であるテーブル学生とテーブルユーザーがいます。学生からの情報を保存し、ユーザーを作成し、IDuserをテーブルstudentのuser_idに設定したい
学生モデル:
class Student extends \yii\db\ActiveRecord
{
public $username;
public $password;
public $email;
......
public function rules()
{
return [
[['name', 'lastname', 'tell', 'mobile', 'codemeli', 'birthday' , 'jensiyat', 'address', 'fatherName', 'user_id', 'created'], 'required'],
[['tell', 'mobile', 'codemeli', 'postcode', 'number', 'user_id', 'salary', 'remove'], 'integer'],
['address', 'string'],
['pic','file'],
['username','string'],
['password','string'],
['email','string'],
[['username','password'],'required'],
['email','unique'],
['email','email'],
[['created', 'salary', 'postcode'], 'safe'],
[['name', 'lastname', 'fatherName', 'level'], 'string', 'max' => 50],
[['birthday'], 'string', 'max' => 10],
[['number', 'user_id'], 'unique', 'targetAttribute' => ['number', 'user_id'], 'message' => 'The combination of Number and User ID has already been taken.'],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
.........
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
$user = new User;
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
$ret=$user->save();
$this->user_id = $user->id;
return $ret ? $user : null;
}
}
actionCreate:
public function actionCreate()
{
$model = new Student();
if ($model->load(Yii::$app->request->post())) {
// $model->
$model->pic = UploadedFile::getInstance($model, 'pic');
$username = Yii::$app->request->post('username');
$password = Yii::$app->request->post('password');
$email = Yii::$app->request->post('email');
$model->created = time();
$model->number = 0;
$model->remove = 1;
$model->level = 0;
$model->salary = 0;
if (!empty($model->pic->extension)) {
$name = time() . '.' . $model->pic->extension;
$model->pic = $name;
if ($model->save()) {
$model->img->saveAs('uploads/' . $name);
}
}
var_dump($model->getErrors());
die();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
わからない
同様の質問
私たちのウェブサイトで同様の質問で答えを見つけてください。