Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call pluck with multiple table without using string params

If I have the following code:

User.where(users: {id: [1,2,3,4,5] } )
  .joins("left outer join carts on users.id = carts.user_id)
  .pluck("user.id", "user.name", "carts.id")

And this work fine. But I think it is cleaner if I can do something similar to the where clause like:

User.where(users: {id: [1,2,3,4,5] } )
  .joins("left outer join carts on users.id = carts.user_id)
  .pluck(users: [:id, :name], carts : [:id])

Is the second approach possible?

Also to note I know the left_joins method exists but I'm not using it here to make the example clear.

like image 444
New To Blue Avatar asked Mar 14 '26 16:03

New To Blue


1 Answers

That hash syntax won't work - but if you want to avoid using strings you can use Arel to avoid hardcoding the table names:

users, carts = User.arel_table, Cart.arel_table

User.where(id: [1,2,3,4,5]) # you don't need to be specific if its on "this" models table
  .joins("left outer join carts on users.id = carts.user_id")
  .pluck(users[:id], users[:name], carts[:id])
like image 114
max Avatar answered Mar 16 '26 05:03

max



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!