Associating Entities and Handler Functions with the User

Learn to fetch the user from the session and to associate entities with the user.

Till now, all notes were visible to all users. We will add a foreign key user_id to the notes table. The column user_id stores the Id of the user to whom the note belongs.

Then, we will change the handler functions to get the user identifier from the session to carry out the dtabase operations in the user’s context.

Associating notes with users

To associate notes with users, we need to do the following:

  1. Create a new migration that adds the foreign key user_id to the notes table.

  2. Alter the Note model to add user ID to the model structure and methods.

Creating a migration

We begin by creating a new migration to add user_id to the notes table.

bee generate migration add_user_id_to_notes
Creating a migration

This command creates a new file database/migrations/20230924_214415_add_user_id_to_notes.go. In this file, we add the SQL command to add the new column.

Press + to interact
package main
import (
"github.com/beego/beego/v2/client/orm/migration"
)
// DO NOT MODIFY
type AddUserIdToNotes_20230924_214415 struct {
migration.Migration
}
// DO NOT MODIFY
func init() {
m := &AddUserIdToNotes_20230924_214415{}
m.Created = "20230924_214415"
migration.Register("AddUserIdToNotes_20230924_214415", m)
}
// Run the migrations
func (m *AddUserIdToNotes_20230924_214415) Up() {
// use m.SQL("CREATE TABLE ...") to make schema update
m.SQL("ALTER TABLE notes ADD user_id bigint")
}
// Reverse the migrations
func (m *AddUserIdToNotes_20230924_214415) Down() {
// use m.SQL("DROP TABLE ...") to reverse schema update
m.SQL("ALTER TABLE notes DROP COLUMN user_id")
}

Let’s break it down line by line:

  • Lines 21–24: The Up method is defined to specify the action to be taken when this migration is executed.

    • Line 23: Here, we use the m.SQL method to execute a SQL statement that adds a new column called user_id of type bigint to the notes table. This is an upward migration, meaning it applies changes to the schema.

  • Lines 27–30: The Down method is defined to specify the action to be taken when this migration is rolled back or reversed.

    • Line 29: This line uses the m.SQL method to execute an SQL statement that drops the user_id column from the notes table.

Running the migration

To execute ...

Get hands-on with 1400+ tech skills courses.