Does loopback 3 support filters on JSON field of a table ? I am using MySQL database - loopbackjs

Does loopback 3 support filters on JSON field of a table ? I am using MySQL database.
For example, we create table 'events' -
CREATE TABLE events(
id int auto_increment primary key,
event_name varchar(255),
visitor varchar(255),
properties json,
browser json
);
Is there any way to apply filter on json fields 'properties' and 'browser' ?

First of all, MySQL doesn't index JSON column (there is workaround but not supported natively), if you go with MySQL, it can be problem in the near feature.
It think it is not possible because doc says that:
Data source connectors for relational databases don’t support filtering nested properties.
However you can implement your own logic for build-in methods via using operation hooks.
For example
Model - the constructor of the model that will be queried
query - the query containing fields where, include, order, etc.
MyModel.observe('access', function **queryToJsonField**(ctx, next) {
// operation goes here
next();
});
More detailed explanation can be found at doc

Related

Having issues with filtering foreign key through postgrest cURL get request

I've recently hit a brick wall when filtering foreign key through postgrest api, I've been going through the documentation and I can't seem to find a way, the query returns filtered array in addition to results that I don't need, but with a nulled fields. Is there a way to filter null fields too or clean up my api request?
My example look like this:
Table 1 - Orders
SKU
owner_foreign_key(FK) - this is the foreign key I'm using
Table 2 - Vehicles
SKU
owner_name [array] - this is the array I'm looking to filter my query by, provided cURL example
/rest/v1/orders?owner_foreign_key.owner_name=eq.{owner_name}&select=SKU,owner_foreign_key(owner_name)
Solved issue by calling !inner before foreign key field. As shown in the documentation. /facepalm

Define unique columns on ManyToMany in Doctrine

I'm trying to add unique columns on a pivot table created via a ManyToMany association.
I found this page of the documentation explaining how to generate a database unique constraint on some columns with this example:
/**
* #Entity
* #Table(name="ecommerce_products",uniqueConstraints={#UniqueConstraint(name="search_idx", columns={"name", "email"})})
*/
class ECommerceProduct
{
}
But this only works if I create the pivot table via a third entity and, in my case, I created the pivot table using a ManyToMany relation (in the same fashion as this code).
Is there a way to add unique columns on pivot table while still using ManyToMany or do I need to rely on a third entity?
While #Table annotation proposes a uniqueConstraints option, #JoinTable does not. Thus, if you want to add a unique constraint on your association table, you will have to actually create another entity explicitly.
That being said, the default join table should not need anything more than the default configuration set up by Doctrine. Currently, when adding a ManyToMany association, the join table is composed of two fields and a composite primary key relying on both fields is created.
If your association table only contains the two basic fields referring to both sides of your association (which is necessarily the case if you use #ManyToMany), the composite primary key should be all you need.
Here is the generated SQL for the basic example where a User has a ManyToMany association with Group (from this section of the documentation):
CREATE TABLE users_groups (
user_id INT NOT NULL,
group_id INT NOT NULL,
PRIMARY KEY(user_id, group_id)
) ENGINE = InnoDB;
ALTER TABLE users_groups ADD FOREIGN KEY (user_id) REFERENCES User(id);
ALTER TABLE users_groups ADD FOREIGN KEY (group_id) REFERENCES Group(id);
As you can see, everything is properly set up with a composite primary key which will ensure that there can't be duplicate entries for the couple (user_id, group_id).
Of course there is another alternative, Alan!
If you need a Zero to Zero relationship, the only alternative is defining the unique constraint per each pk in the agregated table, to make doctrine figuring out about zero to zero relationship.
The problem is that Doctrine's people hadn't considered zero to zero relationships, so the only alternative for this is manytomany relationship with one unique constraint per pk.
If you have doubts about final-state of your doctrine implementation of your E-R model, I strongly recommend mysql-workbench-schema-exporter. With this php tool, you can easily export your mysql workbench E-R schema to a Doctrine's working classes schema, so you would be able to easily explore all your alternatives ;-)
Hope this helps

Prevent multiple SQL querys with model relations

Is it possible to prevent multiple querys when i use django ORM ? Example:
product = Product.objects.get(name="Banana")
for provider in product.providers.all():
print provider.name
This code will make 2 SQL querys:
1 - SELECT ••• FROM stock_product WHERE stock_product.name = 'Banana'
2 - SELECT stock_provider.id, stock_provider.name FROM stock_provider INNER JOIN stock_product_reference ON (stock_provider.id = stock_product_reference.provider_id) WHERE stock_product_reference.product_id = 1
I confess, i use Doctrine (PHP) for some projects. With doctrine it's possible to specify joins when retrieve the object (relations are populated in object, so no need to query database again for get attribute relation value).
Is it possible to do the same with Django's ORM ?
PS: I hop my question is comprehensive, english is not my primary language.
In Django 1.4 or later, you can use prefetch_related. It's like select_related but allows M2M relations and such.
product = Product.objects.prefetch_related('providers').get(name="Banana")
You still get two queries, though. From the docs:
prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python.
As for packing this down into a single query, Django won't do it like Doctrine because it doesn't do that much post-processing of the result set (Django would have to remove all the redundant column data, since you'll get a row per provider and each of these rows will have a copy of all of product's fields).
So if you want to pack this down to one query, you're going to have to turn it around and run the query on the Provider table (I'm guessing at your schema):
providers = Provider.objects.filter(product__name="Banana").select_related('product')
This should pack it down to one query, but you won't get a single product ORM object out of it, instead needing to get the product fields via providers[k].product.
You can use prefetch_related, sometimes in combination with select_related, to get all related objects in a single query: https://docs.djangoproject.com/en/1.5/ref/models/querysets/#prefetch-related

Model linking to other models based on field values

I'm working on simple ratings and comments apps to add to my project and am looking for advice on creating the models.
Normally, I'd create these database schemas like this:
comment_
id - primary key
type - varchar (buyer_item, buyer_vendor, vendor_buyer)
source_id - int (primary key of the table based on the type)
target_id - int (primary key of the table based on the type))
timestamp - timestamp
subject - varchar
comment - text
rating_
id - primary key
type - varchar (buyer_item, buyer_vendor, vendor_buyer)
source_id - int (primary key of the table based on the type)
target_id - int (primary key of the table based on the type)
timestamp - timestamp
rating - int (the score given, ie: 1-5 stars)
This would let me have simple methods that would allow me to apply comments or ratings to any type of thing by setting the proper type and setting the id's of who submitted it (source_id) what it applies to (target_id), like:
add_comment('user_product', user.pk, product.pk, now, subject, comment)
add_comment('user_vendor', user.pk, vendor.pk, now, subject, comment)
I know in the models you define the relationships to other tables as part of the model. How would I define the relationship in these types of tables where the TYPE field determines what table the SOURCE_ID and TARGET_ID link to.
Or should I omit the relationships from the model and set the joins up when I get the QuerySets?
Or just trash the who common table idea and make a whole bunch of different tables to be used for each relationship (eg: user_ratings, product_ratings, transaction_ratings, etc)?
What's the best practice here? My DBA senses say use common tables, but Django newbie me isn't sure what the natives do.
Thanks!
I think what you are looking for is a Generic Relation, and you can find this type of thing in the contenttypes framework: https://docs.djangoproject.com/en/1.0/ref/contrib/contenttypes/#generic-relations

How to join non-relational models in Django 1.3 on 2 fields

I've got 2 existing models that I need to join that are non-relational (no foreign keys). These were written by other developers are cannot be modified by me.
Here's a quick description of them:
Model Process
Field filename
Field path
Field somethingelse
Field bar
Model Service
Field filename
Field path
Field servicename
Field foo
I need to join all instances of these two models on the filename and path columns. I've got existing filters I have to apply to each of them before this join occurs.
Example:
A = Process.objects.filter(somethingelse=231)
B = Service.objects.filter(foo='abc')
result = A.filter(filename=B.filename,path=B.path)
This sucks, but your best bet is to iterate all models of one type, and issue queries to get your joined models for the other type.
The other alternative is to run a raw SQL query to perform these joins, and retrieve the IDs for each model object, and then retrieve each joined pair based on that. More efficient at run time, but it will need to be manually maintained if your schema evolves.