For example, if I have a post model and a comment model I would normally say that a post hasMany(‘comment’) and a comment belongsTo(‘post’).
Are there situations where I would only specify the hasMany or the belongsTo?
For example, if I have a post model and a comment model I would normally say that a post hasMany(‘comment’) and a comment belongsTo(‘post’).
Are there situations where I would only specify the hasMany or the belongsTo?
There are definitely scenarios where you’d only want one-way relationships. In fact the main app that I work on at our company uses almost entirely one way relationships. For example we have a “productgroup”, "product’ and "instrument’, and instrument ->belongsTo-> product ->belongsTo-> productgroup. We don’t really need productgroup to have references to all the products that belong to it, so we don’t define the other side of the relationship.
So essentially, my rule of thumb is basically “what does this model need access to?”. If it needs a reference to its “parent” (belongsTo) or to all its children (hasMany), define the relationship, if not, don’t. Of course it also may make sense to couple it to the backend data models depending on your use case.
That’s just my two cents, others may have better relationship paradigms. I think it’s pretty safe to say, though, that there are circumstances where you only want/need a one-way relationship.
That makes a lot of sense, thanks!
This is a great question, and I’m still working to find the answer myself.
I’ve been told that it may be wise to avoid specifying the hasMany
side when dealing with very large relationships. This is because calling get()
on a very large hasMany would trigger ember data to resolve the whole relationship, which may be infeasible or impossible when there are 1000+ related records.