Imagine, I have this simple database model (Parent_id, Child_id are Foreing Keys)
Is there a way how to query straight all Toys objects of certain Parent?
Now I query all Children first and then I query the Toys of each Child and add them to a list or dict. But it's not really an elegant way...
I imagine something simple like (Flask_SQLAlchemy)
Toys.query.filter(Toys.child.parent_id == 'some parent id')
Is it possible?
Thank you
Krystof
I expect to get a SQLAlchemy object containing all Toys of certain parent.
You can join Toy to Child and then Child to Parent (SQLAlchemy can work out how to do the joins, assuming you have configured relationships between all the models):
toys = (Toy.query
.join(Child)
.join(Parent)
.filter(Parent.name == 'parent1')
)
Related
I have a model called lists, which has a column called item_ids. item_ids is a JSON column (MySQL) and the column contains array of UUIDs, each referring to one item.
Now when someone creates a new list, I need to search whether there is an existing list with same set of UUIDs, and I want to do this search using query itself for faster response. Also use ActiveRecord querying as much as possible.
How do i achieve this?
item_ids = ["11E85378-CFE8-39F8-89DC-7086913CFD4B", "11E85354-304C-0664-9E81-0A281BE2CA42"]
v = List.new(item_ids: item_ids)
v.save!
Now, how do I check whether a list exists which has item ids exactly matches with that mentioned in query ? Following wont work.
list_count = List.where(item_ids: item_ids).count
Edit 1
List.where("JSON_CONTAINS(item_ids, ?) ", item_ids.to_json).count
This statement works, but it counts even if only one of the item matches. Looking for exact number of items.
Edit 2
List.where("JSON_CONTAINS( item_ids, ?) and JSON_LENGTH(item_ids) = ?", item_ids.to_json, item_ids.size).count
Looks like this is working
You can implement a has many relation between lists and items and then access like this.
List.includes(:item).where('items.id in (?)',item_ids)
To implement has_many relation:
http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
I am having a problem. I have a table tblitems which has a primary key which has a child table tblweeks linked via foreign key. When using json.net to serialize json, even when the reference loop handling is set to referenceloophandling.ignore, it is serlilizing the parent tblitem class for every tblweekof linked to it. I don't want that but I still want some fields from the child class. Is there a way in my linq query to only select some columns from a child table or do I have to break the relationships? I'm confused, this seems like really unexpected behavior.
UPDATE
OK, I kind of have what I want now, I found I could use the select function on the child table to only select certain columns, but what is the best way to garentee the order of the child records? I want to make sure they are ordered by weekof in this example:
var q = from lineITem in db.tblBroadcastEntryItems
where lineITem.broadcastID == Int32.Parse(context.Request.QueryString[0])
select new
{
...,
week = lineITem.tblBroadcastEntryWeeks
.Select(c => new { c.weekof, c.spots, c.id })
};
I have a CASE_MEMBER table with a row for each case member, and a field to indicate the member's role on the case. Let's say role 'Parent' and role 'Child'.
In the universe I've added the CASE_MEMBER table, and created a Parent object and Child object, each object containing a WHERE statement which specifies the correct value of the role field.
Now if I try and create a report with both of these objects, it will join to CASE_MEMBER only once, with a condition of "where role = 'Parent' and role = 'Child'", which is obviously impossible.
So I need to force the query to join to CASE_MEMBER once for each member type. Is the only way to do this by creating multiple aliases of CASE_MEMBER? Or is there another way to do this that also keeps my universe structure looking clean and more resembling the actual data model?
Create an alias of CASE_MEMBER, and include the WHERE condition in the join. So your joins will be:
For CASE_MEMBER to DEMOGRAPHICS:
case_member.member = demographics.memberid and case_member.role='child'
For CASE_MEMBER to DEMOGRAPHICS_PARENT (alias of DEMOGRAPHICS):
case_member.member = demographics_parent.memberid and case_member.role='parent'
Let's say you create (using the field names from your other question), a "Case ID" object from case_member.caseid, "Child SSN" from demographics.ssn, and "Parent SSN" from demographics_parent.ssn. Creating a report with all three of these objects will produce:
SELECT
case_member.caseid,
demographics.ssn,
demographics_parent.ssn
FROM
case_member,
demographics,
demographics demographics_parent
WHERE
(case_member.member = demographics.memberid
and case_member.role='child')
(and case_member.member = demographics_parent.memberid
and case_member.role='parent')
which should produce what you want.
Note that in this example, since we are including BOTH the child and parent table, we will get two rows in the result set. One with a blank child SSN and one with a blank parent SSN. To avoid this, you'd need to put a max() around each one.that
I am looking for a non-recursive solution to make a MySQL query to select all of the leaf nodes (children, grandchildren etc) of a node while only knowing who the direct child of the node is.
Currently I have the following tables:
Nodes:
id (INT)
data (VARCHAR)
Relationships:
parentId (INT)
childId (INT)
childNodeOrder (INT)
The way I have it currently I can only select the direct child nodes of a parent node (for this example let the parent Id = 1):
SELECT * FROM Nodes n
JOIN Relationships r ON r.childId = n.id
WHERE r.parentId = 1
ORDER BY r.childNodeOrder;
Is there any way for me to change this database around easily to not use a recursive call (on my server side code) and to be able to get all of the descendant leaves of a parent?
I so far have looked at questions like this one which would seem like a radical change, and not very easy to switch over...
See the NESTED SET data model, it probably can help here.
http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
Edit: since more context is needed, here are the details.
A parent node will have a left and right attributes that cover a range [left, right].
All the children nodes will be included in that range, so that:
parent.left <= child.left <= child.right <= parent.right.
All leaf nodes have a range of 1, so that left + 1 = right only for leaves.
To get all the leaves from a parent, use a where clause similar to this:
WHERE (left + 1 = right) AND (left >= parent.left) AND (right <= parent.right)
I am working on a project where I need to have data inherit at variable depths, and then be able to return any descendants of a particular piece of data. I am working with geographical regions, so I was thinking about having a "Region" table, and have everything from "North America" to individual neighborhoods such as "Bronx". So, if someone types in "North America", they should also receive results for "Bronx" because "Bronx" is a descendant of "North America" by means of the relationship
North America->United States->New York(State)->New York(City)->Bronx
In my DB I was planning on having the Region table link back to itself with a table that specifies a parent/child relationship between Regions. Here is an example of what I would propose:
Any help would be greatly appreciated!
Do you dont need a new table. A foreign key in major table is enough.
This is my approach:
First problem, design data schema: I keep hierarchis with a foreign key to parent row. It is simply. You have an example with hiererchy regions here:
WOE_ID ISO Name Language PlaceType Parent_ID
20069843 "NA" "Oshana" ENG State 23424987
55921113 "NA" "Ondangwa" ENG County 20069843
...
Second problem, retrieve ascendants/descendants: As you explain, problems comes with select: select some region and all descendants os ascendants. To solve this you should to create a new tree table. This table contains pairs: al combination to a person with all they ancestors (and itself):
region( id, name, id_parent)
region_tree( id, id_ancestor, distance )
Noticie that with this structure is easy to query hierarchies. Sample: all descendants of some region:
select region.*, distance
from
region p
inner join
region_tree t
on ( p.id = t.id)
where
id_ancesor = **someregion.id **
You can play with distance to get only sub-regions, sub-sub-regions, ...
Last problem, keep tree: tree must be all time up to data. You should automatize this: a trigger over region or a store procedure for CRUD operations,