I want to count to an extra field created, the matches from a join. Is this possible in CakePHP?
I have an example of my data that I curently have.
And how would a query look in mySQL for this type of result?
Table:goal
id | name
-----------
1 Goal X
2 Goal Y
Table: tasks
id | name | goal_id
-------------------
1 task1 1
2 task2 1
3 task3 2
4 task4 2
5 task5 2
Result
id | name | matches
-------------------
1 goal1 2
2 goal2 3
MySQL query :
SELECT goal.id, goal.name, Count( * ) AS matches
FROM goal
RIGHT JOIN task ON goal.id = task.goal_id
GROUP BY goal.id
CakePHP : [if you have model with name Goal and Task]
$options['fields'] = array(
'Goal.id',
'Goal.name',
'count(*) AS matches'
);
$options['joins'] = array(
array(
'table' => 'tasks',
'alias' => 'Task',
'type' => 'Right',
'conditions' => array(
'Goal.id = Task.goal_id'
)
)
);
$options['group'] = array('Goal.id');
$result = $this->Goal->find('all', $options);
mysql should be that:
Select goal.id,goal.name,Count(*) From goal RIGHT JOIN tasks on goal.id=tasks.goal_id Group by goal.id
CakePHP, can't tell you without testing...
Related
I have a simple Database:
Table 1: Object Table 2: Data
id | type | added object_id | key | value
------------------------ -----------------------------
1 | app | 2017 1 | name | ...
2 | app | 2017 2 | name | ...
3 | win | 2017 2 | version | ...
2 | dev_name | ...
2 | lang | ...
i created a simple pagination to show only 5 object from type apps with their infomation from the data table:
example code:
$sth = $dbh->prepare("SELECT * FROM object WHERE type = 'app' LIMIT 5");
$sth->execute;
$object = $sth->fetchAll(PDO::FETCH_ASSOC);
foreach($object as $rows) {
$sth = $dbh->prepare("SELECT * FROM data WHERE id = $rows['id']");
$sth->execute;
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
echo $data['name'];
echo $data['version'];
echo $object['added'];
...
Is there a better way? because this is a very bad solution, i want to query only one time where i get an fetch array like this:
array(
// app with id = 1 in object table
[1] => array(
// data from the app with id = 1 in data table
[name] => ...
[version] => ...
[dev_name] => ...
[lang] => ...
// app with id = 2 in object table
[2] => array(
// data from the app with id = 2 in data table
[name] => ...
[version] => ...
[dev_name] => ...
[lang] => ...
...
one query:
SELECT * FROM object inner join data on data.id_object=object.id WHERE object.type = 'app' LIMIT 5
This query return information from two table with associate data.
I think that's what you want
If you want to group by id of the first table you can also execute this query
SELECT * FROM object inner join data on data.id_object=object.id WHERE object.type = 'app' group by object.id LIMIT 5
or
SELECT Distinct(object.id), object.type, .... FROM object inner join data on data.id_object=object.id WHERE object.type = 'app' LIMIT 5
Consider for string comparison use LIKE instead of =
I'm fairly new to sql and am trying to get data from table X when the user is not in table Y with the combination of player id and world id AND the player access is 2.
Let me explain a little furter:
Table X (user table)
+-----------+----------+------------+
| uid | access | more data |
+-----------+----------+------------+
| 1 | 2 | .... |
| 2 | 1 | .... |
| 3 | 2 | .... |
+-----------+----------+------------+
Table Y (worlds)
+-----------+-----------+
| userUuid | worldUuid |
+-----------+-----------+
| 1 | 1 |
| 2 | 2 |
| 3 | 2 |
+-----------+-----------+
When I want to get all users which I can still add to world 1 I want to get the user info from user 3.
User 1 already is in world 1, user 2 does not have access level 2 and user 3 isn't in world 1 yet and does have access level 2.
I'm using medoo and this is my statement at the moment:
$database->select("User", [
"[>]UserInWorld" => ["uid" => "userUid"]
], [
"uid",
"displayname",
"surname",
"email"
], [
"AND" => [
"worldUuid[!]" => $worldUuid,
"access" => 2
]
]);
The worldUuid will be the world I want to get user to add for.
When use the ->debug() the query looks like this:
SELECT "uid","displayname","surname","email"
FROM "User"
LEFT JOIN "UserInWorld" ON "User"."uid" = "UserInWorld"."userUid"
WHERE "worldUuid" != '4dafb8c0-57234ff2-03eb-af7f7a5e'
AND "access" = 2
EDIT: I posted a sollution using medoo below
If I understand you correctly, you should be able to do something like this:
SELECT
uid,
displayname,
surname,
email
FROM
User
LEFT JOIN UserInWorld ON User.uid = UserInWorld.userUid AND worldUuid = 1
INNER JOIN (
SELECT DISTINCT
userUid
from
UserInWorld
WHERE
worldUuid != 1
) AS InOtherWorld ON InOtherWorld.userUid = User.uid
WHERE
access = 2
AND UserInWorld.userUid IS NULL
The left join will connect people in the world where possible and then UserInWorld.userUid IS NULL will effectively strip it down to those that aren't in the world.
you said:
am trying to get data from table X when the user is not in table Y with the combination of player id and world id AND the player access is 2
If I've understood it should be:
select * from X where X.access = 2 and X.uid not in (
select Y.userUuid from Y
)
After a good night sleep I figured out how to do this using the medoo class
$database->select("User", [
"[>]UserInWorld" => ["uid" => "userUid"]
], [
"uid",
"displayname",
"surname",
"email"
], [
"AND" => [
"OR" => [
"worldUuid[!]" => [$worldUuid],
"worldUuid" => NULL
],
"access" => 2
],
"GROUP" => "uid"
]);
Whereby the $worldUuid the world is I want to select users for.
This will make the following sql statement:
SELECT "uid","displayname","surname","email" FROM "User"
LEFT JOIN "UserInWorld" ON "User"."uid" = "UserInWorld"."userUid"
WHERE ("worldUuid" NOT IN ('1') OR "worldUuid" IS NULL)
AND "access" = 2
GROUP BY "uid"
This will select all (unique) user who do not have a world already OR are in the world I'm getting users for AND they have access level 2
Ok, so here's my table structure:
+--------------------------+ +----------------+ +-------------------------------+
| pages | | menus | | menu_pages |
+--------------------------+ +----+-----------+ +-------------------------------+
| id | title | slug | | id | name | | menu_id | page_id | parent_id |
+-------+---------+--------+ +----+-----------+ +---------+---------+-----------+
| 1 | Home | index | | 1 | default | | 1 | 1 | 0 |
+-------+---------+--------+ +----+-----------+ +---------+---------+-----------+
| 2 | About | about | | 2 | footer | | 1 | 2 | 0 |
+-------+---------+--------+ +----+-----------+ +---------+---------+-----------+
| 3 | Test 1 | test-1 | | 1 | 3 | 2 |
+-------+---------+--------+ +---------+---------+-----------+
| 4 | Test 2 | test-2 | | 1 | 4 | 2 |
+-------+---------+--------+ +---------+---------+-----------+
| 5 | Test 3 | test-3 | | 1 | 5 | 4 |
+-------+---------+--------+ +---------+---------+-----------+
So basically, we have pages, menus, and a menu_pages linking table which specifies the menu, the page, and the parent of each menu item.
Here's my query:
$query = "SELECT pages.id, pages.title, pages.slug, menu_pages.parent_id
FROM menus, pages, menu_pages WHERE menus.name = '$menu'
AND menus.id = menu_pages.menu_id
AND pages.id = menu_pages.page_id";
$results = $db->Query($query);
Here's the question: How do I get the menu items properly nested under their respective parents in an array? I've tried quite a few things already, but none of them worked beyond simply 2 levels, so I won't clutter up the question with it. Obviously I need some kind of recursion in PHP, or to modify my query maybe in a way that I can get the SQL to return them properly?
It should look something like this in the output:
[0] => array(
'id' => 1,
'title' => 'Home',
'slug' => '/',
'parent_id' => '0'
)
[1] => array(
'id' => 2,
'title' => 'About',
'slug' => 'about',
'parent_id' => 0,
'sub_menu' => array(
[0] => array(
'id' => 3,
'title' => 'Test 1',
'slug' => 'test-1',
'parent_id' => 2
)
[1] => array(
'id' => 4,
'title' => 'Test 2',
'slug' => 'test-2',
'parent_id' => '2',
'sub_menu' => array(
[0] => array(
'id' => 5,
'title' => 'Test 3',
'slug' => 'test-3',
'parent_id' => 4
)
)
)
)
)
Thanks for the help!
This isn't quite as simple as it first sounds - if you want to get into how to do it with SQL, you are looking for a recursive sql statement.
Unfortunately mysql doesn't support this directly, and you would need to write a body of code to get it working. There is an example of how to do it here. Not simple.
http://explainextended.com/2009/03/17/hierarchical-queries-in-mysql/
In case you're interested in how to pick this apart, you would implement it in Oracle like this:
SELECT p.id, p.title, p.slug, mp.parent_id, level
FROM menu_pages mp
JOIN pages p ON ( p.id = mp.page_id )
JOIN menus m ON ( m.id = mp.menu_id )
CONNECT BY PRIOR mp.page_id = mp.parent_id
START WITH ( m.name = 'default' AND mp.parent_id = 0 )
You are basically saying:
START WITH a query for the top level of the menu
CONNECT that back to the result set by joining the parent to the child
You end up with a result set like this:
id title slug parent level
------------------------------------
1 Home index 0 1
2 About about 0 1
3 Test 1 test-1 2 2
4 Test 2 test-2 2 2
5 Test 3 test-3 4 3
All this actually gives you in addition to what you already have is:
The "level" of each point in the menu.
If a sub menu appeared multiple times in your structure it would be repeated correctly.
Sections of the menu that are not connected properly will not be returned.
So, for small, simple and consistent menus it's probably over-kill anyway.
Plus, even in this case you would need to process this in PHP to get the structure you're looking for.
So, using that as inspiration you can see how you could implement it in mysql by just doing the post processing.
You start off with your original query:
SELECT pages.id
, pages.title
, pages.slug
, menu_pages.parent_id
FROM menus
, pages
, menu_pages
WHERE menus.name = 'default'
AND menus.id = menu_pages.menu_id
AND pages.id = menu_pages.page_id
You can then loop over this result and build the array structure yourself manually.
In order to avoid the problem of recursion, we're instead going to take advantage of the fact that we can have two variables pointing at the same data structure - we're going to use references so that changing the value of the variable in one reference will change the value of the variable in the other.
I.E. The difficulty you get is finding the right point in the hierarchy to add each child. With references you don't have to.
Create an empty menu array
Loop over the results from your SQL statement
Create a copy of each menu item and put it into a simply indexed store (by the id of the item)
If you have the root menu item, add it to your menu array (as a reference)
If you don't have the root menu item, find the parent in your simple store and add your new item to it.
At the end you should have the nice nested structure you're looking for.
Like this:
<?php
// As if it came back from mysql...
// Assumed that it's ordered so that every possible parent appears before all its childern
$aResults = array( array( 'id' => 1, 'title' => 'Home', 'slug' => 'index', 'parent_id' => 0 )
, array( 'id' => 2, 'title' => 'About', 'slug' => 'about', 'parent_id' => 0 )
, array( 'id' => 3, 'title' => 'Test 1', 'slug' => 'test-1', 'parent_id' => 2 )
, array( 'id' => 4, 'title' => 'Test 2', 'slug' => 'test-2', 'parent_id' => 2 )
, array( 'id' => 5, 'title' => 'Test 3', 'slug' => 'test-3', 'parent_id' => 4 ) );
// the menu you're creating
$aMenu = array();
// the simple store of the menu items you're going to use to find the parents
$aBaseMenuIndex = array();
foreach( $aResults as $aMenuItem ) {
$aMenuItem['sub_menu'] = array();
// add your menu item to the simple store
$aBaseMenuIndex[ $aMenuItem['id'] ] = $aMenuItem;
if ( $aMenuItem['parent_id'] == 0 ) {
// if it's a base menu item, add it to the menu
$aMenu[] =& $aBaseMenuIndex[ $aMenuItem['id'] ];
} else {
// if it's not a base item, add it to the sub menu, using the simply indexed store to find it
// adding it here will also add it to $aMenu, as $aMenu contains a reference to this
$aBaseMenuIndex[ $aMenuItem['parent_id'] ]['sub_menu'][] =& $aBaseMenuIndex[ $aMenuItem['id'] ];
}
}
var_dump( $aMenu );
alright best way for me to explain is by giving an example
Table 1
ID | name | class
-------------------------
1 | first name | a
2 | second name | b
Table 2
ID | name_id | meta_key | meta_value |
-------------------------------------------------------
1 | 1 | image | someImage.jpg |
2 | 1 | description | very long description |
3 | 2 | image | someImage_2.jpg |
4 | 2 | description | very long description 2 |
I am trying to select name and class from Table 1, and also all the records from Table 2 that has the same name_id as ID (in Table 1).
Here is the query i have now:
SELECT
table1.name,
table1.class,
table2.name_id,
table2.meta_key,
table2.meta_value
FROM
table1
LEFT JOIN
table2 ON ( table1.ID = table2.name_id )
WHERE
table1.ID = '2'
This works and return an array with as many elements as the Table 2 entries that has name_id = 2
Is there a way to return an array with 1 the result from first table, and another array with results from the second table ?
Update:
The ideal results will be:
$result['table1'][0] = array('name' => 'second name',
'class' => 'b')
$result['table2'][0] = array('name_id' => 2,
'meta_key' => 'image',
'meta_value' => 'someImage_2.jpg')
$result['table2'][1] = array('name_id' => 2,
'meta_key' => 'description',
'meta_value' => 'very long description 2')
hopes that makes sense.
I'd split the result array AFTER fetching it from the database...
//Assuming your result-set is assigned to $result:
$table1_keys = array('id', 'name', 'class');
$table2_keys = array('id', 'name_id', 'meta_key', 'meta_value');
$table1_results = array();
$table2_results = array();
foreach($result as $key => $val) {
if(in_array($key, $table1_keys)) {
$table1_results[] = $val;
}
if(in_array($key, $table2_keys)) {
$table2_results[] = $val;
}
}
After this, your result-set should be split into two arrays: $table1_results and $table2_results.
Hope this helps you.
I don't believe there's a way to do it in SQL but I'd label each table so it can be done generically in PHP.
SELECT
':table1',
table1.name,
table1.class,
':table2',
table2.name_id,
table2.meta_key,
table2.meta_value
FROM ...
Although personally I'd just do this.
SELECT 'table1', table1.*, ':table2', table2.*
FROM ...
That makes it easier to duplicate entire rows between client and server and reduces maintenance when you decide to add a new field.
However in your query you are duplicating table1 for each row returned so perhaps this would be better.
SELECT
table1.*,
table2a.meta_value AS image,
table2b.meta_value AS description
FROM
table1
LEFT JOIN
table2 AS table2a ON ( table1.ID = table2a.name_id AND table2a.meta_key = 'image' )
LEFT JOIN
table2 AS table2b ON ( table1.ID = table2b.name_id AND table2b.meta_key = 'description' )
WHERE
table1.ID = '2'
With help from others on here, I've got a nested loop on the go that pull a list of months from one sql table and then, for each of those months, it goes through an events table and pulls the respective events.
Table structures are along the lines of:
MonthTable
ID | MonthShort | MonthLong
1 | 2012Oct | October 2012
2 | 2012Sep | September 2012
EventTable
ID | MonthID | Event | Guests | Adults | Children
1 | 1 | Wedding | 200 | 150 | 50
2 | 1 | Bar Mitzvah | 100 | 50 | 50
3 | 1 | Funeral | 100 | 50 | 50
4 | 2 | Birthday | 50 | 30 | 20
5 | 2 | Birthday | 300 | 200 | 100
6 | 2 | Wedding | 200 | 180 | 20
My loop works so that it populates menu A with all available months, then populates menu B with all of the events for that month. You can then click on the event and it displays the relevant information - this is where I'm a bit stuck.
The arrays I've got are similar to the following, the guests array is what I'm trying out atm:
$events = array();
$months = array();
$guests = array();
while ($row = mysql_fetch_array($result)) {
$months[$row["MonthID"]] = $row["MonthLong"];
$events[$row["MonthID"]][] = $row["Event"];
$guests[$row["MonthID"]][] = $row["Guests"];
}
I use a foreach to populate menu B with ($events[$x] as $event). The screen for each event will have an entry similar to the following and this is what I'd like to do (obviously I know this won't work bu it should serve for illustrative purposes):
echo ' Number of guests: ' . print_r($guests[$x])
With guests and events both on the same counter I though it would allow me to print the array entry in the relevant position.
So what I'd like it if you click on "October 2012" and then select "Funeral", the screen would say:
Number of guests: 100
There are actually several dozen records per event but no point going into all of them...
Apologies for the rambling and if this makes no sense! I'm new to PHP and am only really stuck on this bit.
SQL query is built on the following:
$sql = "
SELECT
a.id, b.id AS monthId, a.event, b.monthshort, b.monthlong
FROM
events_table_name AS a
INNER JOIN
month_table_name AS b ON b.id = a.monthId
ORDER BY
b.id, a.id ASC
";
You need make use of the index in the foreach statement. I mean
foreach ($events[$x] as $i => $event) {
...
echo ' Number of guests: ' . print_r($guests[$x][$i]);
}
I would go for a different data structure in PHP. How about this? You might have to change your SQL query to get it, but this is the data structure I'd aim for:
$months = array(
'1' => array(
'long' => 'October 2012',
'events' => array(
'1' => array(
'name' => 'Wedding',
'guests' => '200'
),
'2' => array(
'name' => 'Bar Mitzvah',
'guests' => '100'
),
'3' => array(
'name' => 'Funeral',
'guests' => '100'
)
)
),
'2' => array(
// etc.
)
);
This way, you're able to look up a month; for each month, its events; for each event, its attendance and name.