Is it possible to have a conditional relationships?

Screen Shot 2020-03-19 at 4.57.04 PM

It always looks at the client profile as the type is set as CLIENT as default. Is there any way to look up and check the data to change the type?

Thank you

2 Likes

Hi @argelasidera!

You can make two relations, AdminProfile and ClientProfile

For example

// In controller
if (profile ==='ADMIN') {
  return User.query().with('AdminProfile').fetch()
}
return User.query().with('ClientProfile').fetch()

You can’t send params to relationship with with(), but you can, when you do something like user.profile('ADMIN')

3 Likes

I already get that if i want the specific user.

const user = await User.find(params.id)
const userProfile = await user.profile(user.profile_type).fetch()
user.profile = userProfile

But what I want is to get all users with their profiles. On your example either admin or client is gonna fetch. Anyway thank you for the idea. :innocent:

1 Like

Can you check this package, maybe you can use it. https://www.npmjs.com/package/adonis-lucid-polymorphic

3 Likes

Thanks! :star_struck:

1 Like