Count quantity of books by category, separate tables - mysql

I'm using Laravel 5 and I need to know the number of books by category, these data I will use on google charts.
I have the code below that I use to find out the number of users by sex. However, the data is in the same table.
$data = DB::table('books')
->select(
DB::raw('category_id as category'),
DB::raw('count(*) as number'))
->groupBy('category')
->get();
$array[] = ['Category', 'Number'];
foreach($data as $key => $value)
{
$array[++$key] = [$value->category->name, $value->number];
}
$test = json_encode($array);
Using the same logic as above, how can I get the number of books by category?
I have the Books table:
ID | Name | ID_CATEGORY
1 Laravel 20
2 Java 20
Category table :
ID | Name
20 Programming
Could you help me in this situation?

You should just group by your ID_CATEGORY column instead of sex.
If you want to construct such array as before, you probably want the name of category. That would be easy if you used Eloquent. You would have $value->category->Name_Category available. If you want those preloaded instead of a query for every value, just add ->with('category') to the query and you'll have it.
If you are not using Eloquent, you should just load the category table separately, key it, and use $categories[$value->ID_CATEGORY]->Name_Category.
Other comments
DB::raw('sex as sex') is equivalent to sex.
++$key seems redundant, you could just push to the end by assigning to $array[].
Array with a header row is not very JSON. Typically you'd have key:value pairs all of the time.
You can construct the array using collection methods.
If you don't have good reasons for the opposite, you should stick to Laravel naming conventions.
I would probably not create an array myself, but do your example as something like this:
$stats = User::select('sex', DB::raw('count(*) as number'))
->groupBy('sex')
->get();
$stats->setVisible(['sex', 'number']);
return $stats;

Related

Add multiple count fields of contained model to query in cakephp 3

I want to have in my model, instead of the complete set of entries of the models contained by another one, just the quantity of them. I could do this by adding the "size" field to the resultset, but I'd like to do this in the query, as I want to paginate and order the results dinamically. I am using this code, but for some reason, if the first count is different from zero, both count fields have the same value, which is the value of the second count field.
$query = $this->Users->find('all')
->contain(['Likes','Favs']);
$query
->select(['like_count' => $query->func()->count('Likes.id')])
->leftJoinWith('Likes')
->group(['Users.id'])
->autoFields(true);
$query
->select(['fav_count' => $query->func()->count('Favs.id')])
->leftJoinWith('Favs')
->group(['Users.id'])
->autoFields(true);
$this->paginate['sortWhitelist'] = [
'name',
'email',
'last_login',
'fav_count',
'like_count',
];
I would like to know why this happens and if there is any other way to do what I attempt, which would be to have ('name', email, 'last_login', quantity of entries in Likes with the user's id, quantity of entries in Favs with the user's id). I have tried using join() to do the left join, but I haven't been able to obtain the result I want.
If you have multiple joins, then you need to count with DISTINCT, eg:
COUNT(DISTINCT Likes.id)
This is because your result will contain Likes * Favs number of rows, as for every joined like, all favs will be joined, ie for 2 likes and 10 favs you'd end up with 20 rows in total. A regular COUNT() would include every single one of those rows.
Also note that you don't need to repeat all that grouping, etc stuff, and you can use a callable for select() to avoid breaking up the builder.
$query = $this->Users
->find('all')
->select(function (\Cake\ORM\Query $query) {
return [
'like_count' => $query->func()->count(
$query->func()->distinct(['Likes.id' => 'identifier'])
),
'fav_count' => $query->func()->count(
$query->func()->distinct(['Favs.id' => 'identifier'])
),
];
})
->autoFields(true)
->contain(['Likes', 'Favs'])
->leftJoinWith('Likes')
->leftJoinWith('Favs')
->group(['Users.id']);
Using the functions builder to generate the DISTINCT is a workaround, as there is no API yet that would allow to specifically generate a keyword. The result will be something like DISTINCT(Likes.id), but it will work fine, the parentheses will be interpreted as part of the expression after the keyword, not as part of a function call.

Laravel GroupBy and Count using eloquent model

I have a table
'new_comments'
with fields
id,user_id,
title,
comment_description
I have another table named
'comments_upvote'
having
field user_id,
post_id,
likes
id of new_comments and post_id of comments_upvote table are same. we have to take those comments which have the most likes. how we fetch that data.
$ud = Comments_upvote::select('post_id')->groupby('post_id')-
>orderby(DB::raw('count(likes)'), 'desc')->get();
$postid = array();
foreach ($ud as $key => $value) {
$postid[] = $value->post_id;
}
$data = DB::table('new_comments')->whereIn('id',$postid)->get();
but the problem is that i have to count all likes whose value = 1 how can we do that.
If you showed us some code you'd get a more concrete answer, but here's a quick outline of what you need: define your relationships (make sure you use your custom foreign key), use whereHas, group by post_id count, and sort by count descending.
So I'm guessing you have at least two models NewComment and CommentUpvote (you should). In the NewComment define a 1:n relationship:
public function upvotes(){
$this->hasMany('App\CommentUpvote', 'post_id');
}
Then in your controller (again, guessing, since you didn't show any code):
$bestComments = NewComment::whereHas('upvotes', function($query){
$query->select('post_id', DB::raw('count(*) as total'))->groupBy('post_id')->orderBy('total', 'desc');
})->get();
Disclaimer: this is untested and off the top of my head, but should nugde you in the right direction.

Trouble counting rows with specific value - Doctrine, Symfony2, mysql

I'm working on querying my mysql database via doctrine in a symfony2 app. I have a basic table set up that includes an id number ('id'), name ('name'), and a last column for if the person has been contacted ('contacted'), depicted with 0 or 1. I can query and get the number of total inquiries (depicted in the controller with $inquiryCountTotal just fine.
I'm struggling to count the rows that have been contacted. I figure I can either COUNT the rows with a value of 1 in the contacted column or I could just SUM all the rows in the contacted column.
For some reason it seems to be summing the ids, as I have 8 ids and it's spitting a number of 36.
Where am I going wrong? Thanks in advance!
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('EABundle:Inquiry')
->findBy(array(), array('id'=>'DESC'));
$inquiryCountTotal = $em->createQuery("
SELECT count(id)
FROM EABundle:Inquiry id
")->getSingleScalarResult();
//This is the part I'm struggling with...
$inquiryCount = $em->createQuery("
SELECT sum(contacted)
FROM EABundle:Inquiry contacted
")->getSingleScalarResult();
return $this->render('EABundle:Inquiry:index.html.twig', array(
'entities' => $entities,
'inquiryCount' => $inquiryCount,
'inquiryCountTotal' => $inquiryCountTotal
));
}
Doctrine is interpreting the alias as the id of the entity.
Try this:
$inquiryCount = $em->createQuery("
SELECT sum(i.contacted)
FROM EABundle:Inquiry i
")->getSingleScalarResult();

SQL issue: one to many relationship and EAV model

Good evening guys,
I'm a newbie to web programming and I need your help to solve a problem inherent to SQL query.
The database engine I'm using is MySQL and I access it via PHP, here I'll explain a simplified version of my database, just to fix ideas.
Let's suppose to work with a database containing three tables: teams, teams_information, attributes. More precisely:
1) teams is a table containing some basic information about italian football teams (soccer, not american football :D), it is formed by three fields: 'id' (int, primary key), 'name' (varchar, team name), nickname (Varchar, team nickname);
2) attributes is a table containing a list of possible information about a football team, such as city (the city where team plays its home match), captain (team captain's fullname), f_number (number of fans) and so on. This table is formed by three fields: id (int, primary key), attribute_name (varchar, an identifier for the attribute), attribute_desc (text, an explanation of the meaning of attribute). Each record of this table represents a single possible attribute of a football team;
3) teams_information is a table where some information, about teams listed in team table, are available. This table contains three fields: id (int, primary key), team_id (int, a foreign key which identifies a team), attribute_id (int, a foreign key which identifies one of the attributes listed in attributes table), attribute_value (varchar, the value of the attribute). Each record represents a single attribute of a single team. In general, different teams will have a different number of information, so for some teams a large number of attributes will be available while for other teams only a small number of attributes will be available.
Note that relation between teams and teams_information is one to many and the same relation exists between attributes and teams_information
Well, given this model my purpose is to realize a grid (maybe with ExtJS 4.1) to show user the list of italian football team, each record of this grid will represent a single football team and will contain all possible attributes: some fields may be empty (because, for considered team, the correspondent attribute is unknown), while the others will contain the values stored in teams_information table (for the considered team).
According to the above grid's field are: id, team_name and a number of fields to represent all the different attributes listed in 'attributes' table.
My question is: can I realize such a grid by using a SINGLE SQL query (maybe a proper SELECT query, to fetch all data I need from database tables) ?
Can anyone suggest me how to write a similar query (if it exists) ?
Thanks in advance for helping me.
Regards.
Enrico.
The short answer to your question is no, there is no simple construct in MySQL to achieve the result set you are looking for.
But it is possible to carefully (painstakingly) craft such a query. Here is an example, I trust you will be able to decipher it. Basically, I'm using correlated subqueries in the select list, for each attribute I want returned.
SELECT t.id
, t.name
, t.nickname
, ( SELECT v1.attribute_value
FROM team_information v1
JOIN attributes a1
ON a1.id = v1.attribute_id AND a1.attribute_name = 'city'
WHERE v1.team_id = t.id ORDER BY 1 LIMIT 1
) AS city
, ( SELECT v2.attribute_value
FROM team_information v2 JOIN attributes a2
ON a2.id = v2.attribute_id AND a2.attribute_name = 'captain'
WHERE v2.team_id = t.id ORDER BY 1 LIMIT 1
) AS captain
, ( SELECT v3.attribute_value
FROM team_information v3 JOIN attributes a3
ON a3.id = v3.attribute_id AND a3.attribute_name = 'f_number'
WHERE v3.team_id = t.id ORDER BY 1 LIMIT 1
) AS f_number
FROM teams t
ORDER BY t.id
For 'multi-valued' attributes, you'd have to pull each instance of the attribute separately. (Use the LIMIT to specify whether you are retrieving the first one, the second one, etc.)
, ( SELECT v4.attribute_value
FROM team_information v4 JOIN attributes a4
ON a4.id = v4.attribute_id AND a4.attribute_name = 'nickname'
WHERE v4.team_id = t.id ORDER BY 1 LIMIT 0,1
) AS nickname_1st
, ( SELECT v5.attribute_value
FROM team_information v5 JOIN attributes a5
ON a5.id = v5.attribute_id AND a5.attribute_name = 'nickname'
WHERE v5.team_id = t.id ORDER BY 1 LIMIT 1,1
) AS nickname_2nd
, ( SELECT v6.attribute_value
FROM team_information v6 JOIN attributes a6
ON a6.id = v6.attribute_id AND a6.attribute_name = 'nickname'
WHERE v6.team_id = t.id ORDER BY 1 LIMIT 2,1
) AS nickname_3rd
I use nickname as an example here, because American soccer clubs frequently have more than one nickname, e.g. Chicago Fire Soccer Club has nicknames: 'The Fire', 'La Máquina Roja', 'Men in Red', 'CF97', et al.)
NOT AN ANSWER TO YOUR QUESTION, BUT ...
Have I mentioned numerous times before, how much I dislike working with EAV database implementations? What should IMO be a very simple query turns into an overly complicated beast of a potentially light dimming query.
Wouldn't it be much simpler to create a table where each "attribute" is a separate column? Then queries to return reasonable result sets would look more reasonable...
SELECT id, name, nickname, city, captain, f_number, ... FROM team
But what really makes me shudder is the prospect that some developer is going to decide that the LDQ should be "hidden" in the database as a view, to enable the "simpler" query.
If you go this route, PLEASE PLEASE PLEASE resist any urge you may have to store this query in the database as a view.
I'm going to take a slightly different route. Spencer's answer is fantastic, and it addresses the issue quite well, but there's still a large underlying problem.
The data that you are trying to display on the site is over-normalized in the database. I won't elaborate, since, again, Spencer's answer highlights the issue pretty well.
Rather, I'd like to recommend a solution that denormalizes the data a bit.
Convert all of your Team data into a single table with many columns. (If there is Player data that isn't covered in the question, that would be a second table, but I'll gloss over that for now.)
Sure, you'll have a whole bunch of columns, and a lot of the columns might be NULL for a lot of the rows. It's not normalized, and it's not pretty, but here's the huge advantage that you gain.
Your query becomes:
SELECT * FROM Teams
That's it. That gets displayed right to the website and you are done. You might have to go out of your way to realize this schema, but it would be totally worth the time investment.
I think what you're saying is that you want the rows in the attributes table to appear as columns in the result recordset. If this is correct, then then in SQL you would use PIVOT.
A quick search on SO seems to indicate that there is no PIVOT equivalent in MySql.
I wrote a simple PHP script to generalize spencer's idea to solve my issue.
Here's the code:
<?php
require_once('includes/db.config.php'); //this file performs connection to mysql
/*
* Following function requires a table name ($table)
* and a number of service fields ($num). Given those parameters
* it returns the number of table fields (excluding service fields).
*/
function get_fields_number($table,$num,$conn)
{
$query = "SELECT * FROM $table";
$result = mysql_query($query,$conn);
return mysql_num_fields($result)-$num; //remember there are $num service fields
}
/*
* Following function requires a table name ($table) and an array
* containing a list of service fields names. Given those parameters,
* it returns the list of field names. That list is contained within an array and
* service fields are excluded.
*/
function get_fields_name($table,$service,$conn)
{
$query = "SELECT * FROM $table";
$result = mysql_query($query,$conn);
$name = array(); //Array to be returned
for ($i=0;$i<mysql_num_fields($result);$i++)
{
if(!in_array(mysql_field_name($result,$i),$service))
{
//currently selected field is not a service field
$name[] = mysql_field_name($result,$i);
}
}
return $name;
}
//Below $conn is db connection created in 'db.config.php'
$query = "SELECT `name` FROM `detail_arg` WHERE visibility = 0";
$res = mysql_query($query,$conn);
if($res===false)
{
$err_msg = mysql_real_escape_string(mysql_error($conn));
echo "{success:false,data:'".$err_msg."'}";
die();
}
$arg = array(); //list of argument names
while($row = mysql_fetch_assoc($res))
{
$arg[] = $row['name'];
}
//Following function writes the select subquery which is
//necessary to build a column containing a single attribute.
function make_subquery($attribute) //$attribute contains attribute name
{
$query = "";
$query.="(SELECT incident_detail.arg_value ";
$query.="FROM incident_detail ";
$query.="INNER JOIN detail_arg ";
$query.="ON incident_detail.arg_id = detail_arg.id AND detail_arg.name='".$attribute."' ";
$query.="WHERE incident.id = incident_detail.incident_id) ";
$query.="AS $attribute";
return $query;
}
/*
echo make_subquery("date"); //debug code
*/
$subquery = array(); //list of subqueries
for($i=0;$i<count($arg);$i++)
{
$subquery[] = make_subquery($arg[$i]);
}
$query = "SELECT "; //final query containing subqueries
$fields = get_fields_name("incident",array("id","visibility"),$conn);
//list of 'incident' table's fields
for($i=0;$i<count($fields);$i++)
{
$query.="incident.".$fields[$i].", ";
}
//insert the subqueries
$sub = implode($subquery,", ");
$query .= $sub;
$query.=" FROM incident ORDER BY incident.id";
echo $query;
?>

How can I store multiple rowsets in 1 variable sql

I have a join where i have a many to many relationship between categories and courses....I use multiple join in CodeIgniter with Active Record. My code looks like this:
$query = $this->db->select('*')
->from('subscriptions')
->where('subscriptions.user_id', $user_id)
->join('courses', 'courses.id=subscriptions.course_id')
->join('course_categories', 'course_categories.course_id=courses.id')
->join('categories', 'categories.id=course_categories.category_id')
->join('tutor_profiles', 'tutor_profiles.id=courses.tutor_id')
->get();
I have a problem retrieving multiple categories for 1 course...i want to have something like categories = array(JOIN RESULT). I mean i want to retrieve the results from the join of the categories in 1 sql variable that is an array and loop the results after.
How can I do this? Or do I need to make 2 queries?
You should try to serialize your result and save it in db