我正在使用yii2-advanced
。我有几张表:
tb_user
:(iduser(PK)
,username
),tb_profile
:(id
,iduser(FK)
),tb_status
:(id
,iduser(FK)
)我的问题是,在我按下注册按钮后,如何在iduser(PK)
和tb_user
上iduser(FK)
tb_profile
插入tb_status
。
有一段时间我想我必须对bevahiours()
模型上的User
函数进行一些修改,我发现了一些错误,或者在表上添加了trigger
语法? (我认为这不是一个好方法)。
有没有人可以帮助我,如何解决我的问题?
这是修改前的User
模型:
<?php
namespace common\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;
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%user}}';
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'timestamp' => [
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => 'created_at',
ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_at',
],
'value' => function () {return date('Y-m-d h:m:s');},
],
];
}
/**
* @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 function getId()
{
return $this->getPrimaryKey();
}
}
?>
Controller
:
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
答案 0 :(得分:2)
我的一个项目中有类似的情况,我有两个表,如user
,user_image
其中user_id
是添加路径的外键。
对于这种情况,您可以使用以下任一方法
1.单击signup
按钮,在两个表中插入记录。您必须相应地编写更新操作。
$user = new User();
$user->name = "John"
$user->email = "John@gmail.com"
//Add if any other fields in table
$user->save(); //save the record
$user_image = new UserImage();
$user_image->user_id = $user->id;
$user_image->image = "image path"
//Add any other images here
$user_image->save();//save the record
2.您也可以致电create
的{{1}}行动并执行相同操作。如果您使用此方法,您可能还需要使用任何其他唯一列来查找该用户的UserImage
并使用它来插入新记录,例如在我的表中id
是唯一列,所以我可以在email
中编写以下代码并获取UserImage
id
通过这种方式,您可以根据需要使用代码
谢谢