Skip to content
Advertisement

Sort records with an associated field

I want to order records with associated records in GORM V2.

I have two structs:

Now, I can load all the records with:

How can I now order these records with a field from the ClientProfile struct?

I tried without success:

This throws the following error:

ERROR: missing FROM-clause entry for table “client_profiles” (SQLSTATE 42P01)

Advertisement

Answer

Find with Preload queries the clients table first, and then queries the client_profiles table with the IDs from the first, thus it can’t sort the first query by data from the second one.

Since this is a HasOne relationship you can use Joins Preloading which actually does use a single query for both entities. Then you will be able to sort by the related entity’s field:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement