Foreign key in yii2

hy yii developers

i am learning yii from scratch and i am stopped at adding foreign key in yii

look this is what i want i have 2 tables user and store and i want user_id in store table when a user registered a new store

user table structure:

`CREATE TABLE IF NOT EXISTS `user` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `username` varchar(255) NOT NULL,
  `mobile` bigint(20) NOT NULL,
  `password` varchar(255) NOT NULL,
  `authkey` varchar(255) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  PRIMARY KEY (`user_id`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;` 

store table structure:

`CREATE TABLE IF NOT EXISTS `store` (
  `seller_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `store_name` varchar(255) NOT NULL,
  `store_no` bigint(10) NOT NULL,
  `address` varchar(255) NOT NULL,
  `pincode` bigint(10) NOT NULL,
  `type` varchar(255) NOT NULL,
  `mobile` bigint(10) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  PRIMARY KEY (`seller_id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;`

i want user_id in store table if user registered a new store thank you

plzz ignore my mistake and interested to read code if exists it online if topic is same as mine

Hi @fezzymalek
First of all, create foreign key constraint in store table:

ALTER TABLE store ADD CONSTRAINT fk_store_user_user_id FOREIGN KEY (user_id) REFERENCES user (user_id);

Or you can use migrations. More info here.

Now you need to update Store model by adding new method for getting related User model

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

Or you can generate new Store model using Gii.

Last thing you need is to ensure that everytime when user creates new Store model, user’s user_id is saved too. There are many ways how to do it, for example you can edit actionCreate in StoreController to request user_id value of current user ( Yii::$app->user->user_id ) and write it into user_id attribute of Store model:

public function actionCreate()
{
    $model = new Store();
    $model->user_id = Yii::$app->user->user_id;

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

thanks a lot buddy its working :smiling_face_with_three_hearts: