I have been using go-lang and gorm to build web apps for a while. Though gorm
provids very good documentation, I think it lacks some real-time examples. Here is
what I have learned how to use gorm for advanced queries. Most importantly to get data
from multiple tables that are not directly related.
Let me try explaining the concepts with three use cases.
Consider following models
The models are simple. Movie have foreign key to Launguage and Artist
have many-to-many relationship with Movie with artist_movies as
intermediate table. Important thing to note here is Artist have no direct
relationship with Language model. Lets populate the db with some data(Im
using postgres here, though you can you any database)
After populating above modes in db, the tables look like below
Now, the time for actual query. How would you make the following queries
Get the list of all artist who acted in “english” movies
Get the list the artists for movie “Nayagan”
Get the list of artists for movies “3 idiots”, “Shamitab” and “310 to Yuma”
Get list of all artist who acted in “english” movies:
Get the list of all artists who acted in movie “Nayagan”
Get the list of artists who acted in any of the movies “3 idiots”, “Shamitab” and “310 to Yuma”
Without Joins, the above queries using gorm would involve lots of where
clause and loops. But using Joins its just one simple database query.
the link to complete program used in this article.
See you with more real-time examples for more advanced queries using gorm next time. Happy