Parse.com many-to-many with attributes - many-to-many

I have a many-to-many relation between "Ingredient" and "Recipe". I know I can add and remove object from the relation using
var Recipe = Parse.Object.extend("Recipe");
var Ingredient = Parse.Object.extend("Ingredient");
var recipe = new Recipe();
var ingredient = new Ingredient();
ingredient.id = "abcDef1234"; //random
var recipe_ingredients = recipe.relation("recipe_ingredients");
recipe_ingredients.add(ingredient);
But this only adds the ingredient. How do I also store a field like "quantity" along with each ingredient added? (Like extra attributes on a pivot table?)
Thanks!

You can't. This is one of Parse's many limitations. You'll have to abandon the builtin relations model, create your own join table. That is, create a new object type which has two pointers: the first, the source object; the second, the target. This forms the relation. You can then add fields on this table to act as attributes on the relationship. If you want, you can keep a pointer from the object that originally held the relation, targeting the join table entry.
Of course, once you realise that this doubles the number of requests you're using (each database hit is a "request" apparently), then you start to realise that the Parse database model coupled with their charging model scales about as well as building skyscrapers from matchsticks.

Related

multi-tenancy Join or multiple Select queries postgres

I am implementing multi tenancy using single database and separating data for each tenant using a tenant_id. This id is passed in the jwt token as well. I have two tables right now genre and books. genre table has columns like
tenant_id, genre_id, ..... and books table has columns genre_id, book_id, book_name, ....
So 1 genre can have multiple books associated with it and 1 tenant can have multiple genres associated with it.
Now every time a book is fetched or updated I want to make sure the right person is making these calls.
I know of two ways to do it.
First way:
Make two queries. First fetch the book, get the associated genre_id in the object. Then fetch that genre and compare the jwt tenant_id with the tenant_id inside this genre object.
Something like this
const book= await ReadBook(req.query.book_id); // fetches my book from db
const genre = await ReadBook(book.genre_id); // fetches the genre from db
if (genre.tenant_id === jwtToken.tenant_id) {..} // compare if same or not
Second way:
Do this query in db
select b.*, g.tenant_id as tenant_id
from book_data b, genre_data g
where b.book_id = '0eokdpz0l' and g.tenant_id = 'M1MzgzMDM' and b.genre_id = g.genre_id
Which method is more efficient?
If theres a more efficient method then these then please let me know too
It's good practice to stick to ORM abstraction if possible, while minimising how much and how often data is transferred to/from db. Sequelize is able to construct an equivalent to that query for you, with the necessary joins and filters on the ids. Something among the lines of:
Books.findAll({
where: {book_id: '0eokdpz0l'},
include: [{
model: Genre,
where: {tenant_id : jwtToken.tenant_id}
}]
}).then(books => {
/* ... */
});
Running multiple queries in sequence not only adds latency due to additional round trips to/from db (and possibly connection setup if you're not pooling or holding them open) but it's also moving more bytes of data around, needlessly. tenant_id mismatch on db would send back a shorter message with an empty result. Checking it on client side requires downloading data even when you'll have to discard it.

How to interact with a join table in bookshelf and knex?

I want to create an entry in a join table using bookshelf. I followed the instructions on the bookshelf website here. (Models instantiation with bookshelf and tables creation with knex).
Is there a way, upon creation of a new Book, to add values to the authors_books table WITHOUT creating an authors_books model/collection?
What should I add to this:
//Books references the Books collection that holds the Book models
var book = new Book({
title: title,
base_url: req.headers.origin
});
book.save().then(function(newBook) {
Books.add(newLink);
res.send(200, newBook);
});
Yes, of course, it's quite simple.
You need two models, Book and Author. Both have belongsToMany relationship defined and withPivot as well. withPivot lists the attributes that are in the junction table, see more here: http://bookshelfjs.org/#Model-withPivot
Afterwards, you call updatePivot, to update the attributes that are in author_book table only.

cakephp retrive data from one table excluding the associated tables

I am struggling with a basic problem. i am using cake php 2.5. i try to apply the find query in the company model and receiving all the data from companies and with its associations, but i only want to receive the data from company table and want to exclude the data from rest of relationships, can anyone help me with this. below are my queries.
$this->loadModel('Company');
$fields=array('id','name','logo','status');
$conditions=array('status'=>1);
$search_companies = $this->Company->find('first',
compact(array('conditions'=>$conditions,'fields'=>$fields)));
print_r($search_companies);die();
echo json_encode($search_companies);die();
With out seeing your data output, I am just going to take a stab at the problem.
Inside your $search_companies variable you are getting a multidimensional array probably with the other values of the other tables.
Why not just select the one array:
$wantedData = $search_companies['Company'];
// The key Company (which is the model) should be the data you are wanting.
Try setting model's recursive value to -1
$this->Company->recursive = -1;
$search_companies = $this->Company->find('first',
compact(array('conditions'=>$conditions,'fields'=>$fields)));
With this you will not fire the joins queries and therefore you only retrieve model's information.
Cakephp provide this functionality that we can unblind few/all associations on a any model. the keyword unbindModel is used for this purpose. inside the unblindModel you can define the association type and model(s) name that you want to unblind for that specific association.
$this->CurrentModelName->unbindModel(array('AssociationName' => array('ModelName_Youwwant_unblind')));

What is the best way to merge 2 tables with Active Record and Mysql

We need to allow users to customize their entities like products... so my intention was to have a product table and a custom_product table with just the information the users are allowed to change.
When a client goes to the product I want to merge the information, means I want to merge the two tables - the custom overwrites the default Products table.
I know that in mysql there exists a ifnull(a.title, b.title) way but I was wondering if there is any nice and efficient way to solve this in Rails 4 with Active Record. Assume that the products and custom products table have just 2 columns, ID and TITLE
I think you can convert both objects to JSON and then handle their params as a hash, using the merge method:
class Product
end
class Customization
belongs_to :product
end
a = Product.find(...)
b = a.customization
c = JSON(a.to_json).merge(JSON(b.to_json).reject!{|k,v| v.nil?})
Therefore c will contain all params from Product eventually overridden by those in Customization which are not nil.
If you still want to use a Product object with hybrid values (taken from Customization) you can try this:
a.attributes = a.attributes.merge(b.attributes.reject!{|k,v| v.nil?})
In this case a will still be a Product instance. I would recommend to keep the same attributes in both models when doing this.

Can I specify a set of base parameters for a Linq-to-sql DataContext?

I have a LINQ-to-SQL DataContext that represents a parent-child relationship of Products to Prices. I'm iterating through a list of products and retrieving the prices for each one. The problem is that the tables behind both the Products and Prices contain a list of Products or Prices for multiple environments, determined by a 3 field complex key. I want to retrieve the Products and Prices for only one of those environments.
I can do this be specifying a long where clause in each LINQ query consisting of the product key and the complex environment key, something like this:
var price = ( from condition in conditiontype where condition.MaterialNumber == material && condition.Client == "400" && condition.SalesOrg == "1000" && condition.DistributionChannel == "10" select condition.ConditionDetails[0].ConditionValue );
what I'd like to be able to do is to specify the Client, SalesOrg, and DistributionChannel globally for the DataContext so that all I need to specify in the query itself is the Product ID (MaterialNumber). That way when I starting querying our Production environment a simple change to the DataContext will change what environment I'm querying.
Is this possible? Either a brief code sample or pointers to the background theory would be wonderful!
You could have a pre-written Expression<T> which you then have those values in it:
public Expression<Func<int>> GetPrices = p => // do Lambda here
Alternatively you can put properties into your DataContext (remember, it's a partial class so it's easy to extend) which you set and are then read in by your expression.