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
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
Most helpful comment
If you have eagerloaded a relationship, then you can check it as.