Return filtered records from a returned set of data from two tables - ruby

I have three tables:
- Venue
- Space (belongs to Venue)
- Included Space (belongs to Space)
I receive the id of a Venue in the route and return all the related spaces that I know have Included Spaces(a field called num_included_spaces__c on the Space record that maintains a count of its children). Now that I have all the related parent Spaces for that Venue, I need to find all of the Included Spaces for them.
An Included Space is still a Space, it just happens to have a parent that resides in the same table. I'm trying to turn this:
Venue = Rockdog
- Space = Upstairs
- Space = Media Room
- Space = Courtyard
- Space = Downstairs
- Space = Front Patio
- Space = Indoor Bar
Into this:
Venue = Rockdog
- Space = Upstairs
-- Included Space = Media Room
-- Included Space = Courtyard
- Space = Downstairs
-- Included Space = Front Patio
-- Included Space = Indoor Bar
The Included Spaces table has belongs_to__c and space__c as fields, where belongs_to__c is the id of the parent space and space__c is the id of the child. So i'm looking to find all the Included Spaces where belongs_to_c matches the id of any #spaces returned below
#sub_spaces = Space.where("venue__c = ? AND num_included_spaces__c = ?", params[:venue],0)
#spaces = Space.where("venue__c = ? AND num_included_spaces__c > ?", params[:venue],0)
How would I write this Active Record Query for #included_spaces?

my database schema.
mysql> describe venues;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
4 rows in set (0,00 sec)
mysql> describe spaces;;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| venue_id | int(11) | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
5 rows in set (0,00 sec)
ERROR:
No query specified
mysql> describe included_spaces;;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| space_id | int(11) | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
5 rows in set (0,00 sec)
ERROR:
No query specified
Below function will somehow give you the result you need (in console ofcourse ) however it's not a good solution - it queries database more than needed. However it is the easy -))
def foo id
v = Venue.find(id)
puts v.name
v.spaces.each do |space|
puts space.name
space.included_spaces.each do |spis|
puts spis.name
end
end
end
You can also try a more complex query sth like,
mysql> SELECT spaces.name, included_spaces.name FROM `spaces` INNER JOIN `venues` ON `venues`.`id` = `spaces`.`venue_id` INNER JOIN `included_spaces` ON `included_spaces`.`space_id` = `spaces`.`id` WHERE `spaces`.`venue_id` = 1
-> ;
+------------+-----------+
| name | name |
+------------+-----------+
| Upstairs, | Front |
| Upstairs, | Patio, |
| Upstairs, | Indoor |
| Upstairs, | Bar |
| Downstairs | Media |
| Downstairs | Room, |
| Downstairs | Courtyard |
+------------+-----------+
7 rows in set (0,00 sec)
which should be translated to active record as
Space.joins(:venue)
.joins(:included_spaces)
.where(venue_id: 1)
.select('spaces.name, included_spaces.name')

Related

Laravel get value from db with columns key/value

I have a table on my DB with these columnns:
+-----------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
| value | varchar(255) | NO | | NULL | |
+-----------------+---------------------+------+-----+---------+----------------+
I would access to value values by name.
For example I have these datas:
+----+------------+------------+
| id | name | value |
+----+------------+------------+
| 1 | start_date | 2020-01-01 |
| 2 | end_date | 2021-01-01 |
+----+------------+------------+
I would to get '2020-01-01' by 'start_date'.
I tried this code, but I'm not satisfyed because with this code I get all values of the row, not only the value expected.
Configuration::get()->keyBy('start_date');
I'm not sure I was clear.
Let me know.
Thanks a lot!!
Assuming you want to get an array of key/value pairs, and each key in the name column is unique, you can simply use pluck() (https://laravel.com/docs/8.x/collections#method-pluck):
$configuration = Configuration::pluck('value', 'name');
dd($configuration);
// ['start_date' => '2020-01-01', 'end_date' => '2021-01-01']
Then, you'd use simply array access to use these configuration settings where applicable:
$startDate = $configuration['start_date']; // '2020-01-01'
$endDate = $configuration['end_date']; // '2021-01-01'
...

How to use ResultSet to fetch the ID of the record

I have got a table with name table_listnames whose structure is given below
mysql> desc table_listnames;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
+-------+--------------+------+-----+---------+----------------+
2 rows in set (0.04 sec)
It has got sample data as shown
mysql> select * from table_listnames;
+----+------------+
| id | name |
+----+------------+
| 6 | WWW |
| 7 | WWWwww |
| 8 | WWWwwws |
| 9 | WWWwwwsSSS |
| 10 | asdsda |
+----+------------+
5 rows in set (0.00 sec)
I have a requirement where if name not found under the table , i need to insert or else do nothing
I am achieving it this way
String sql = "INSERT INTO table_listnames (name) SELECT name FROM (SELECT ?) AS tmp WHERE NOT EXISTS (SELECT name FROM table_listnames WHERE name = ?) LIMIT 1";
pst = dbConnection.prepareStatement(sql);
pst.setString(1, salesName);
pst.setString(2, salesName);
pst.executeUpdate();
Is it possible to know the id of the record of the given name in this case

MySQL has many through [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
1- Users may have many classrooms
2- Classrooms may have many users
3- Users may have many payments in their classrooms
how can I get a classroom payments through its users with SQL?
how can I get sum of the payments of a user per classroom?
-- Payments Table: --
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| user_id | int(11) | NO | | NULL | |
| amount | int(11) | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
-- Users Table: --
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
-- Classrooms Table: --
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
-- Classroom_User Table: --
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| user_id | int(11) | NO | | NULL | |
| classroom_id| int(11) | NO | | NULL | |
+-------------+--------------+------+-----+---------+----------------+
Without testing, I'd say:
SELECT p.amount, u.name, c.name
FROM payments p, users u, classrooms c, classroom_user ct
WHERE ct.user_id = u.id
AND ct.classroom_id = c.id
AND u.id = p.user_id
However: it's not clear what your tables are about. For instance: one record in the payments table can result in multiple records in the result set, namely when there are multiple records in the classroom_user table for the same user.
Something in your database design feels wrong, but it's hard to tell what's wrong without more info.
Suppose that you want to get the payments for each classroom. In that case, your database design is wrong because you only know the amount each user paid in total, not the amount the user paid per classroom.
The payments table should look like this:
+-------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| classroom_user_id | int(11) | NO | | NULL | |
| amount | int(11) | NO | | NULL | |
+-------------------+--------------+------+-----+---------+----------------+
In that case, you'd have:
SELECT c.name, u.name, p.amount
FROM payments p, users u, classrooms c, classroom_user ct
WHERE p.classroom_user_id = ct.id
AND ct.classroom_id = c.id
AND ct.user_id = u.id
Or, if you want to get the total amount per classroom:
SELECT c.name, SUM(p.amount)
FROM payments p, classrooms c, classroom_user ct
WHERE p.classroom_user_id = ct.id
AND ct.classroom_id = c.id
GROUP BY c.id
Note that I didn't test this. I don't have your database.

Using Closure_tree gem instead of Awesome nested set

Hi I followed the link to set up closure_tag gem.
When i tried to use closure_tree syntax in the following way (newStructure.find_or_create_by_path(parent) instead of newStructure.move_to_child_of(parent)) ... got the following error :
"Can't mass-assign protected attributes: ancestor, descendant, generations"
is this the correct way of using newStructure.find_or_create_by_path(parent) ?
def self.import(path)
newStructure = FileOrFolder.find(:first, :conditions=>["fullpath = ?", path])
if newStructure
return newStructure
end
newStructure = FileOrFolder.new
newStructure.fullpath = path
pathbits = path.split('/')
newStructure.name = pathbits.last
newStructure.save
parentpath = path.sub(/#{Regexp.escape(pathbits.last)}$/, '')
if parentpath.length > 1
parentpath.sub!(/\/$/,'')
parent = FileOrFolder.find(:first, :conditions=>["fullpath = ?", parentpath])
unless parent
parent = FileOrFolder.import(parentpath)
end
#newStructure.move_to_child_of(parent);
**newStructure.find_or_create_by_path(parent);**
end
newStructure.save
return newStructure
end
database table looks like :
mysql> select * from testdb7.file_or_folders limit 10;
+------+-----------+------+------+----------+------------------------+---------------------+---------------------+
| id | parent_id | lft | rgt | fullpath | name | created_at | updated_at |
+------+-----------+------+------+----------+------------------------+---------------------+---------------------+
| 6901 | NULL | NULL | NULL | NULL | | 2013-06-25 18:49:04 | 2013-06-25 18:49:04 |
| 6902 | 6901 | NULL | NULL | NULL | devel | 2013-06-25 18:49:04 | 2013-06-25 18:49:04 |
| 6903 | 6902 | NULL | NULL | NULL | Bcontrol | 2013-06-25 18:49:04 | 2013-06-25 18:49:04 |
| 6904 | 6903 | NULL | NULL | NULL | perfect | 2013-06-25 18:49:04 | 2013-06-25 18:49:04 |
| 6905 | 6904 | NULL | NULL | NULL | matlab | 2013-06-25 18:49:04 | 2013-06-25 18:49:04 |
| 6906 | 6905 | NULL | NULL | NULL | test | 2013-06-25 18:49:04 | 2013-06-25 18:49:04 |
| 6907 | 6906 | NULL | NULL | NULL | smoke | 2013-06-25 18:49:04 | 2013-06-25 18:49:04 |
| 6908 | 6907 | NULL | NULL | NULL | Control_System_Toolbox | 2013-06-25 18:49:04 | 2013-06-25 18:49:04 |
| 6909 | 6908 | NULL | NULL | NULL | tsmoke_are.m | 2013-06-25 18:49:04 | 2013-06-25 18:49:04 |
| 6910 | 6908 | NULL | NULL | NULL | tsmoke_bode.m | 2013-06-25 18:49:04 | 2013-06-25 18:49:04 |
+------+-----------+------+------+----------+------------------------+---------------------+---------------------+
FileOrFolder Load (14560.8ms) SELECT `file_or_folders`.* FROM `file_or_folders` INNER JOIN `file_or_folder_hierarchies` ON `file_or_folders`.`id` = `file_or_folder_hierarchies`.`descendant_id` INNER JOIN (
SELECT ancestor_id
FROM `file_or_folder_hierarchies`
GROUP BY 1
HAVING MAX(`file_or_folder_hierarchies`.generations) = 0
) AS leaves ON (`file_or_folders`.id = leaves.ancestor_id) WHERE `file_or_folder_hierarchies`.`ancestor_id` = 147 ORDER BY `file_or_folder_hierarchies`.generations asc
EXPLAIN (13343.7ms) EXPLAIN SELECT `file_or_folders`.* FROM `file_or_folders` INNER JOIN `file_or_folder_hierarchies` ON `file_or_folders`.`id` = `file_or_folder_hierarchies`.`descendant_id` INNER JOIN (
SELECT ancestor_id
FROM `file_or_folder_hierarchies`
GROUP BY 1
HAVING MAX(`file_or_folder_hierarchies`.generations) = 0
) AS leaves ON (`file_or_folders`.id = leaves.ancestor_id) WHERE `file_or_folder_hierarchies`.`ancestor_id` = 147 ORDER BY `file_or_folder_hierarchies`.generations asc
EXPLAIN for: SELECT `file_or_folders`.* FROM `file_or_folders` INNER JOIN `file_or_folder_hierarchies` ON `file_or_folders`.`id` = `file_or_folder_hierarchies`.`descendant_id` INNER JOIN (
SELECT ancestor_id
FROM `file_or_folder_hierarchies`
GROUP BY 1
HAVING MAX(`file_or_folder_hierarchies`.generations) = 0
) AS leaves ON (`file_or_folders`.id = leaves.ancestor_id) WHERE `file_or_folder_hierarchies`.`ancestor_id` = 147 ORDER BY `file_or_folder_hierarchies`.generations asc
+----+-------------+----------------------------+--------+------------------------------------------------------------------------------------+----------------------------------+---------+--------------------+---------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------------------------+--------+------------------------------------------------------------------------------------+----------------------------------+---------+--------------------+---------+---------------------------------+
| 1 | PRIMARY | file_or_folder_hierarchies | ref | index_file_or_folders_on_ans_des,index_file_or_folder_hierarchies_on_descendant_id | index_file_or_folders_on_ans_des | 4 | const | 15 | Using temporary; Using filesort |
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 104704 | Using where; Using join buffer |
| 1 | PRIMARY | file_or_folders | eq_ref | PRIMARY | PRIMARY | 4 | leaves.ancestor_id | 1 | Using where |
| 2 | DERIVED | file_or_folder_hierarchies | index | NULL | index_file_or_folders_on_ans_des | 8 | NULL | 1340096 | |
+----+-------------+----------------------------+--------+------------------------------------------------------------------------------------+----------------------------------+---------+--------------------+---------+---------------------------------+
I'm the author of closure_tree. 4.2.3 is on it's way with the fix for attr_accessible. I'm just waiting for Travis to finish testing it.
It looks like your whole import method could be replaced with this line:
# Assumes that path is a string that looks like this: "/usr/local/bin/ruby"
def import(path)
FileOrFolder.find_or_create_by_path(path.split("/"))
end
This assumes you have this FileOrFolder setup:
class FileOrFolder < ActiveRecord::Base
acts_as_tree
before_create :set_fullpath
def set_fullpath
if root?
self.fullpath = "/#{name}"
else
self.fullpath = "/#{parent.ancestry_path.join("/")}/#{name}"
end
end
end
Please take a look at the spec directory. You'll find tons of other examples.

magento database structure?

Currently am working with magento project..
in which i have stucked on the point ..
that is when admin add any subcategory/category
by
Manage category -> custome design
here its gives two option like
Active from and Active to..
can anyone, who know about magento database, tell me where or in which table this two value store
Thanks for any suggestion or help!
I've listed the attributes for catalog categories below. Since categories are an EAV type, you'll need to look in a particular subtable to get your values. In this case, custom_design_from and custom_design_to are datetime values, and the name of your entity is catalog_category_entity, so the table you want is catalog_category_entity_datetime.
Next problem you'll find is getting the right attribute ID. Since they're liable to change, here's the SQL query to run in order to grab them:
select attribute_id, attribute_code from eav_attribute where entity_type_id = 3 and attribute_code in ('custom_design_from', 'custom_design_to');
I get 52 and 53, but YMWV. Hope that helps!
Thanks,
Joe
+----------------------+--------------+
| attribute_code | backend_type |
+----------------------+--------------+
| name | varchar |
| is_active | int |
| url_key | varchar |
| description | text |
| image | varchar |
| meta_title | varchar |
| meta_keywords | text |
| meta_description | text |
| display_mode | varchar |
| landing_page | int |
| is_anchor | int |
| path | static |
| position | static |
| all_children | text |
| path_in_store | text |
| children | text |
| url_path | varchar |
| custom_design | varchar |
| custom_design_apply | int |
| custom_design_from | datetime |
| custom_design_to | datetime |
| page_layout | varchar |
| custom_layout_update | text |
| level | static |
| children_count | static |
| available_sort_by | text |
| default_sort_by | varchar |
| include_in_menu | int |
+----------------------+--------------+
Active from is an attribute whose attribute_code is custom_design_from(attribute_id 57) and Active To is an attribute whose attribute_code(attribute_id 58) is custom_design_to.
This both attributes value are stored in database table `catalog_category_entity_datetime`.
Check above table with row like value of entity_id is your category id, attribute_id is 57 and active from value is store in value field of table same active to value is stored in value field with entity_id is your category id, attribute_id is 58.

Resources