1

I wonder if it is possible to select by a condition in a preloaded object. For example, I have tables User and Profile (one to one). So I need to get all Users with Profiles where sex is female.

I thought it can be done by something like this:

Preload("UserProfile").Where("user_profile.sex = ?", "female")

But it returns something like:

pq: missing FROM-clause entry for table \"user_profile\"

2
  • I belive the table is actually called user_profiles Apr 12, 2019 at 17:06
  • I found, I have to use Joints: Joins("left join trade_items on trade_items.id = trade_requests.trade_item_id") and then Where("trade_items.request_type = ?", "SELL") Apr 12, 2019 at 17:12

2 Answers 2

1

Preloading doesn't join the tables specified. You need to explicitly join the table in question:

Preload("UserProfile").Joins("LEFT JOIN user_profile ON user.id = user_profile.user_id")
    .Where("user_profile.sex = ?", "female")

...Assuming your primary key is called id, and foreign key is called user_id.

0

I also faced the same issue in a recent project. I found the below solution to work for me.

var users []User
Preload("UserProfile","sex = ?","female").Find(&users)

and then check for

user.profile!=nil

The issue in this approach is it will load all users.

But in your case, it can be another way around.

var profiles []Profile
Preload("User").where("sex = ?","female").Find(&profiles)

I hope this will solve your problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.