Associating Entities and Handler Functions with the User
Learn to fetch the user from the session and to associate entities with the user.
We'll cover the following...
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:
Create a new migration that adds the foreign key
user_idto thenotestable.Alter the
Notemodel 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
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.
package mainimport ("github.com/beego/beego/v2/client/orm/migration")// DO NOT MODIFYtype AddUserIdToNotes_20230924_214415 struct {migration.Migration}// DO NOT MODIFYfunc init() {m := &AddUserIdToNotes_20230924_214415{}m.Created = "20230924_214415"migration.Register("AddUserIdToNotes_20230924_214415", m)}// Run the migrationsfunc (m *AddUserIdToNotes_20230924_214415) Up() {// use m.SQL("CREATE TABLE ...") to make schema updatem.SQL("ALTER TABLE notes ADD user_id bigint")}// Reverse the migrationsfunc (m *AddUserIdToNotes_20230924_214415) Down() {// use m.SQL("DROP TABLE ...") to reverse schema updatem.SQL("ALTER TABLE notes DROP COLUMN user_id")}
Let’s break it down line by line:
Lines 21–24: The
Upmethod is defined to specify the action to be taken when this migration is executed.Line 23: Here, we use the
m.SQLmethod to execute a SQL statement that adds a new column calleduser_idof typebigintto thenotestable. This is an upward migration, meaning it applies changes to the schema.
Lines 27–30: The
Downmethod is defined to specify the action to be taken when this migration is rolled back or reversed.Line 29: This line uses the
m.SQLmethod to execute an SQL statement that drops theuser_idcolumn from thenotestable.
Running the migration
To execute the ...