Sailsjs / waterline request "where" is not empty

Hy there

Before moving on to the hack / crop method, I wanted to know if there is a built-in query method for checking empty / non-empty relationships from many to many, since I have not been successful in google or doc.

If I take an example in a document, imagine that I want to get the user only if he has Pet or Retrive Pet without an owner through a request.

 // A user may have many pets var User = Waterline.Collection.extend({ identity: 'user', connection: 'local-postgresql', attributes: { firstName: 'string', lastName: 'string', // Add a reference to Pet pets: { collection: 'pet', via: 'owners', dominant: true } } }); // A pet may have many owners var Pet = Waterline.Collection.extend({ identity: 'pet', connection: 'local-postgresql', attributes: { breed: 'string', type: 'string', name: 'string', // Add a reference to User owners: { collection: 'user', via: 'pets' } } }); 

Ps I know how to filter the results after the query is completed, and not what I ask :)

+5
source share
2 answers

There is nothing inline (aka User.hasPet ()) or something like that, so the simple answer is NO

If I know about these problems, I try to write my database in such a way that queries are fast. IE: the user schema will have a hasPets column. Whenever a pet is added / removed, callbacks fall into the user table to mark this field if it has an owner or not. Therefore, I can request User.findAll ({hasPet: true}).

Not much, but it depends on where you need speed.

+3
source

It's a bit late, but I wanted you to know that it is quite easy to do this using the Waterline ORM lifecycle features. I have done this in several of my projects. Basically, use the beforeCreate and beforeUpdate functions to set your flags. For your user, this might look like ...

  var User = Waterline.Collection.extend({ identity: 'user', connection: 'local-postgresql', beforeCreate: function(values, next) { if (values.pets) { values.has_pet = true; } else { values.has_pet = false; } next(); } beforeUpdate: function(values, next) { if (values.pets) { values.has_pet = true; } else { values.has_pet = false; } next(); } attributes: { firstName: 'string', lastName: 'string', // Add a reference to Pet pets: { collection: 'pet', via: 'owners', dominant: true }, has_pet: { type: 'boolean' } } }); 

Then you can query based on the has_pet attribute

+2
source

Source: https://habr.com/ru/post/1210019/


All Articles