Expected known function, got 'count',how can I use count in doctorine? - doctrine-orm

I have table like this
reviews in restaurant table are tied as foreign key with reviews table
Restaurant table
ID| name | reviews
1 | subway | 1,2
2 | macdonald | 3
Review table
ID| review
1 | review about subway1
2 | review about subway2
3 | review about macdonald
Normally I can fetch Resturant data as
$query = $this->em->createQuery(
"SELECT a FROM Restaurant a);
However I would like to order the number of review column.
Now I made sentence like this but in vain.
$query = $this->em->createQuery(
"SELECT a FROM Restaurant a
INNER JOIN Review r
order by count(a.reviews) ");
it shows error like this.
Expected known function, got 'count'

You should have the restaurant ID in the reviews table, so that you skip the complications of having a comma-separated string in the restaurant table.
Restaurant table
ID| name
1 | subway
2 | macdonald
Review table
ID| restaurant ID | review
1 | 1 | review about subway1
2 | 1 | review about subway2
3 | 2 | review about macdonald
Then you can do this:
$query = $this->em->createQuery(
"SELECT a, count(a.reviews) count1 FROM Restaurant a
INNER JOIN Review r
order by count1 ");

Related

How to use prefetch_related to retrieve multiple rows similar to SQL result

I’ve a question about the usage of prefetch_related. Based on my understanding I need to use prefetch_related for reverse foreign key relationships
As an example I have a User(id, name) model and SchoolHistory(id, start_date, school_name, user_id[FK user.id]) model. A user can have multiple school history records.
If I’m querying the database using the following SQL query:
SELECT
user.id,
name,
start_date,
school_name
FROM user
INNER JOIN school_history ON school_history.user_id = user.id
the expected result would be:
| User ID | Name | Start Date | School |
| 1 | Human | 1/1/2022 | Michigan |
| 1 | Human | 1/1/2021 | Wisconsin |
| 2 | Alien | | |
This is the current result that I’m getting instead with ORM and a serializer:
| User ID | Name | school_history
| 1 | Human | [{start_date:1/1/2022 , school:Michigan}, {start_date:1/1/2021 , school:Wisconsin}] |
| 2 | Alien | [] |
This is the ORM query that I’m using:
User.objects.prefetch_related(
Prefetch(
‘school_history’
query_set=SchoolHistory.objects.order_by(‘start_date’)
)
)
Is there a way for the ORM query to have a similar result as SQL? I want multiple rows if there are multiple schools associated with that user

Add column to existing table in rds

I have table in RDS which consists two columns id and user activity at some time exactly values active/away.I get user activity every day so I need to add user activity column every day to that table.Any ideas how to do it?Now I have table with first two columns in RDS,but I am in stuck with how to add columns to that table
+-------------+------------+------------+
| id | 2020-08-13 | 2020-08-14 |
-----------------------------------------
| 12345 | active | away |
You could use an alter table ... add column, but this is not the right way to solve the problem.
In a relational database, you add additional rows for repeated data, not additional columns. So your table should look like this:
+-------------+-------------+------------+
| id | status_date | status |
------------------------------------------
| 12345 | 2020-08-13 | active |
| 12345 | 2020-08-14 | away |
Then you add a new row using an insert.

How do I calculated group averages with a filter in DAX?

I've got data across 2 tables that kind of looks like:
Table 1
Mean | Activity | name_id
---------------------------
1 | Swimming | 1
3 | Basketball | 2
3 | Swimming | 3
9 | Running | 1
5 | Basketball | 3
TypeName | Name_id
------------------
ABC | 1
DEF | 2
GHI | 3
Assuming joins are in place, I want to run the equivalent of this SQL:
select activity, avg(mean)
from table1 a
inner join table2
on table1.name_id = table2.name_id
where table2.name_id = 'DEF'
I got a basic quick measure that does everything except for the filter for 'DEF' name_ids:
Average =
AVERAGEX(
KEEPFILTERS(VALUES('Table1'[Activity])),
CALCULATE(SUM('Table1'[Mean]))
)
I'm stumped as to where exactly I should put a filter. I also tried using CALCULATE as the base function, but was stumped on how to properly run that.

django get latest for each group, group by foreign key

Assume I have something like these models:
class Product(models.Model):
name = models.CharField(max_length=50)
class Sale(models.Model):
product = models.ForeignKey(Product)
sale_date = models.DateField()
I want to get the latest sale for each product. Latest means the latest sale_date. Also, in the same query I want to get the number of products sold for each product.
In SQL terms, I need to group by product_id, to count the number of sales for each product (which is the length of each group). And maybe also to order by date (in each group as well) to get only the latest product sale.
With django ORM I realized I need to somehow use annotate() and maybe in combination with values(). But I still haven't figured how.
Assume I have this products table:
| id | name |
===================
| 1 | Book |
| 2 | Telephone |
And this sales table:
| id | product_id | sale_date |
=================================
| 1 | 1 | 05-02-2015 |
| 2 | 2 | 04-02-2015 |
| 3 | 2 | 03-02-2015 |
| 4 | 1 | 06-02-2015 |
| 5 | 1 | 01-02-2015 |
I want to get output like:
| product_id | name | sale_date | num_sales |
====================================================
| 1 | Book | 06-02-2015 | 3 |
| 2 | Telephone | 04-02-2015 | 2 |
Since 06-02-2015 is the latest sale date for product_id=1 (Book), and 04-02-2015 is the latest date for product_id=2 (Telephone).
from django.db.models import Count, Max
query = Product.objects.annotate(num_sales=Count('sale'))
query = query.annotate(latest_sale_date=Max('sale__sale_date'))
for prod in query.all():
print (prod.pk, prod.name, prod.latest_sale_date, prod.num_sales)
You will get output like:
(1, u'Book', datetime.date(2015, 6, 2), 3)
(2, u'Telephone', datetime.date(2015, 4, 2), 2)
akin to your expected output in the question. Note that whatever kwarg you pass to annotate becomes an attribute on the query result.

Using count in Doctrine2

Count row by Doctrine
I have tables like this
id | name
---------
1 | john
2 | ken
3 | john
4 | ken
5 | ken
6 | haku
when I use this sentence
$em->createQuery("SELECT c.id FROM UserBundle:customer c group by c.name")->getResult()
I can get the pair of first id for each people.
1 | john
2 | ken
6 | haku
However ,I would like to get the count how many times each name appears, like below.
1 | john | 2
2 | ken | 3
6 | haku | 1
How can I make it?
For complicated queries, I'd probably use PDO directly, especially if you don't need to map to an entity.
Here is an example of how to use PDO directly:
$q = "your query here";
$stmt = $em->getConnection()->prepare($q);
$stmt->execute();
$results = $stmt->fetchAll(\PDO::FETCH_ASSOC);
Try this:
$em->createQuery("SELECT c.name, COUNT(c.id) as cnt FROM UserBundle:customer c group by c.name")->getResult();