Lucid: How do you check if a relation is defined?

Created on 21 May 2018  路  9Comments  路  Source: adonisjs/lucid

I have an User and a Cart model like this

class User extends Model {
static boot() {
    super.boot();

    this.addGlobalScope(builder => builder.with('cart'));
  }
  cart() {
    return this.hasOne('App/Models/Cart');
  }
}

class Cart extends Model {
  user() {
    return this.belongsTo('App/Models/User');
  }
}



md5-0b8f0dcfe71f388e83884ff74f443627



// this gets me the "cart" relation as well because of the global scope.
const user = await auth.getUser(); 
if (user.cart) {
    ...
}

how to I check if the user has an associated cart without fetching again?
Boolean(user.cart) // always true, even if the user has no cart

Most helpful comment

If you have eagerloaded a relationship, then you can check it as.

if (user.getRelated('cart')) {
}

All 9 comments

How can you find something exists without fetching it from the database?

this.addGlobalScope(builder => builder.with('cart')); when I do this, isn't it supposed to do eager loading? so const user = await auth.getUser(); is supposed to have prefetched the cart. Or that is not the case?

Please don't ask multiple questions in a single issue. Keep it focused.

If you have eagerloaded a relationship, then you can check it as.

if (user.getRelated('cart')) {
}

sorry for the confusion, but that was related to my initial question.
Thanks for the help. Couldn't find that in the documentation.

Yup I agree, it鈥檚 missing in the docs. I am happy to accept the PR for same ( if you have time )

I'd be happy to help. Will cut some time in the next couple of days and I'll submit it.
Thanks

I think the question is still valid. Maybe you wanna remove the "invalid" tag so someone else can benefit from the answer.

wow I just stumbled on this and what I was writing at this time absolutely needs this... I am grateful for this. Thank you

Was this page helpful?
0 / 5 - 0 ratings

Related issues

babadee08 picture babadee08  路  6Comments

SAGV picture SAGV  路  7Comments

watzon picture watzon  路  3Comments

nwashangai picture nwashangai  路  5Comments

hailwood picture hailwood  路  5Comments