


How to query a model where the embedded value of a relation is equal to a specific value?
When developing and designing database models, sometimes we need to query whether the embedded value in the relationship is equal to a specific value. This problem is often encountered in practical applications, but it may not be easy to solve. In this article, I will introduce you to a model with an efficient way to query whether the embedded value of a relationship is equal to a specific value. No need to worry, I will explain it clearly in concise and easy-to-understand language to help you quickly understand and apply it to actual development. Let’s take a look!
Question content
I have two different models (cars
and types
) that are related to each other (belong to relationships), two of which Models all have an embedded struct
for public data (post
). I want to retrieve certain types
, but only receive answers where the post
's cars
value is equal to a certain value.
shorty said, based on the model below, I want to find all types
where cars.post.published
is equal to true.
Model
type post struct { published bool } type car struct { gorm.model brand string post post `gorm:"embedded"` } type type struct { gorm.model name string carid uint32 car car post post `gorm:"embedded"` }
Using db.preload("car").find(&type)
I was able to get the car
value in the answer object. If I use the where()
function on the car
structure (i.e. where(car{brand: "volvo"}
) I can pass brand
Gets the value, but when using post
(i.e. where(car{post: post {published: true})
) it just returns everything.
I would be better off using the main model that needs to be queried as the basis for the where()
function. For example:
q := Type{Car: Car{Post: Post{Published: true}}} db.Preload("Car").Where(q).Find(&Type)
...but this doesn't seem to work. How to implement such query without using raw sql generator?
Solution
I was able to solve your problem in the following ways. First I'll share the code and then I'll cover the key points worth explaining.
package main import ( "fmt" "gorm.io/driver/postgres" "gorm.io/gorm" ) type Post struct { Published bool } type Car struct { gorm.Model Brand string TypeID int Type Type Post Post `gorm:"embedded"` } type Type struct { gorm.Model Name string CarID int Post Post `gorm:"embedded"` } func main() { dsn := "host=localhost port=54322 user=postgres password=postgres dbname=postgres sslmode=disable" db, err := gorm.Open(postgres.Open(dsn)) if err != nil { panic(err) } db.AutoMigrate(&Car{}) db.AutoMigrate(&Type{}) // uncomment these to seed data // db.Create(&Car{Brand: "Tesla", Type: Type{Name: "SUV", Post: Post{Published: true}}, Post: Post{Published: true}}) // db.Create(&Car{Brand: "Ford", Type: Type{Name: "City", Post: Post{Published: false}}, Post: Post{Published: false}}) var cars []Car if err := db.Debug().Model(&Car{}).Preload("Type").Where(&Car{Post: Post{Published: true}}).Find(&cars).Error; err != nil { panic(err) } for _, v := range cars { fmt.Println(v.Type.Name) } }
Now, let me share some insights.
Structure definition
I changed it slightly to handle this scenario. I removed the car
field from the type
structure and added its counterpart in the car
structure definition.
Settings and Seeds
Then, I set up the database connection through gorm. I synchronize the model defined in the code with the relationship that exists in the database. To demonstrate, I manually seeded some dummy data.
Read logic
Then, I run the query to get the relevant data. I used the following method:
-
debug
: used to record actual sql statements -
model
: used to specify the relationship we want to process -
preload
: used to loadtype
association -
where
: used to specify conditions (in our case, the filter is on the embedded structure) -
find
: used to map results to variables
Please tell me if this helps solve your problem, thank you!
The above is the detailed content of How to query a model where the embedded value of a relation is equal to a specific value?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Yes, MySQL can be installed on Windows 7, and although Microsoft has stopped supporting Windows 7, MySQL is still compatible with it. However, the following points should be noted during the installation process: Download the MySQL installer for Windows. Select the appropriate version of MySQL (community or enterprise). Select the appropriate installation directory and character set during the installation process. Set the root user password and keep it properly. Connect to the database for testing. Note the compatibility and security issues on Windows 7, and it is recommended to upgrade to a supported operating system.

How to create tables using SQL statements in SQL Server: Open SQL Server Management Studio and connect to the database server. Select the database to create the table. Enter the CREATE TABLE statement to specify the table name, column name, data type, and constraints. Click the Execute button to create the table.

Methods to judge SQL injection include: detecting suspicious input, viewing original SQL statements, using detection tools, viewing database logs, and performing penetration testing. After the injection is detected, take measures to patch vulnerabilities, verify patches, monitor regularly, and improve developer awareness.

MySQL can handle multiple concurrent connections and use multi-threading/multi-processing to assign independent execution environments to each client request to ensure that they are not disturbed. However, the number of concurrent connections is affected by system resources, MySQL configuration, query performance, storage engine and network environment. Optimization requires consideration of many factors such as code level (writing efficient SQL), configuration level (adjusting max_connections), hardware level (improving server configuration).

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

The methods to check SQL statements are: Syntax checking: Use the SQL editor or IDE. Logical check: Verify table name, column name, condition, and data type. Performance Check: Use EXPLAIN or ANALYZE to check indexes and optimize queries. Other checks: Check variables, permissions, and test queries.

MySQL uses shared locks and exclusive locks to manage concurrency, providing three lock types: table locks, row locks and page locks. Row locks can improve concurrency, and use the FOR UPDATE statement to add exclusive locks to rows. Pessimistic locks assume conflicts, and optimistic locks judge the data through the version number. Common lock table problems manifest as slow querying, use the SHOW PROCESSLIST command to view the queries held by the lock. Optimization measures include selecting appropriate indexes, reducing transaction scope, batch operations, and optimizing SQL statements.

This article introduces a detailed tutorial on joining three tables using SQL statements to guide readers step by step how to effectively correlate data in different tables. With examples and detailed syntax explanations, this article will help you master the joining techniques of tables in SQL, so that you can efficiently retrieve associated information from the database.
