Your Question

How Many To Many Preload performs conditional query on the intermediate table?

The document you expected this should be explained

db.Preload("role","type = ?",1)->Find(&user);
The above query, prompts an error,
The output is: select * from role where type=1
But I want to be able to do where on the intermediate table somehow
select * from user_role where type=1;

Expected answer

Is there an API implementation that I don't know about? Or how to achieve this effect in other way

Comment From: github-actions[bot]

This issue has been automatically marked as stale because it has been open 360 days with no activity. Remove stale label or comment or this will be closed in 180 days

Comment From: saeidee

Have you tried this? https://gorm.io/docs/preload.html#Custom-Preloading-SQL

Comment From: OneSeven

Have you tried this? https://gorm.io/docs/preload.html#Custom-Preloading-SQL

This doesn't work out, I need to impose a condition to the intermediate table

Comment From: saeidee

For now, you can use it like this:

Gorm How Many To Many Preload performs conditional query on the intermediate table?

Comment From: OneSeven

For now, you can use it like this:

Gorm How Many To Many Preload performs conditional query on the intermediate table?

You seem to have misunderstood me, In your Demo, you simply find out the data in the intermediate table. My requirement is that in a many-to-many association query, the conditions for changing the intermediate table are as follows:

user(id)->userRole(user_id,role_id,type=?)->role(id)

Comment From: saeidee

Based on your issue description, you mentioned querying not updating intermediate table.

db.Preload("role","type = ?",1)->Find(&user);
The above query, prompts an error,
The output is: select * from role where type=1
But I want to be able to do where on the intermediate table somehow
select * from user_role where type=1;

.

Comment From: mostafa-binesh

i have this problem too @saeidee dude, the op wanted to have some condition in the .preload() function not with where() function in your example it would be sth like this

DB.Model(&user).Preload("Roles","some_field = ?","foo").find(&user)

but it doesn't work in gorm and instead of searching in "user_roles" table, it searches in "roles" table

Comment From: mostafa-binesh

because this issue was closed i opened another one

6479

Comment From: jackbaron

I have same the problem. Any solution for this?. I want add cinditional query for intermediate table. But I not found the solution on document