Here is my code:
$qb = $this->_em
->createQueryBuilder();
$query = $qb->select('COUNT(food) as cnt')
->from(Food::class, 'food')
->groupBy('cnt')
->getQuery()->getSQL();
However my expectation like the following query:
SELECT COUNT(f0_.food_id) AS sclr_0 FROM foods f0_ WHERE (f0_.deleted_at IS NULL) GROUP BY sclr_0
The result looks like:
SELECT COUNT(f0_.food_id) AS sclr_0 FROM foods f0_ WHERE (f0_.deleted_at IS NULL) GROUP BY f0_.food_id
Any suggestion?
You'll need to use your query as a subquery, Id do this in raw SQL, but you can get the idea from:
$qb = $this->_em
->createQueryBuilder();
$query = $qb->select('COUNT(food) as cnt')
->from(Food::class, 'food')
->groupBy('cnt')
->getQuery()->getSQL();
$qb2 = $this->_em
->createQueryBuilder();
$query2 = $qb->select('sclr_0')
->from('('.$query.')', 'cnt')
->groupBy('sclr_0 ')
->getQuery()->getSQL();
Related
I have a raw sql query which i run using yii2 Yii::$app->db->createCommand() but then i wonder i how i can use yii's method of writing queries to actualize the same thing.
$m = "SELECT p.basic_plan_amt AS basic,p.premium_plan_amt AS premium,p.daju_plan_amt AS daju,c.name
AS country FROM price p LEFT JOIN country c ON p.country_id = c.id WHERE p.country_id = " .$country_id;
though the above query works well and provide expected result, but then how can i write the same query using the below format
$model = \backend\models\Price::find()->select([p.basic_plan_amt AS basic,p.premium_plan_amt AS
premium,p.daju_plan_amt AS daju,c.name
AS country])->where(['country_id' => $country_id])->all();
Below are the examples of query in yii hope it will help you More reference
Relation Model
$model = User::find()
->with('comments')
->all();
foreach ($model as $user) {
// get data from relation model
$comments = $user->comments;
......
foreach($comments as $comment){
........
}
}
joinWith()
Sample 1:
$model = User::find()
->joinWith('comments')
->all();
Sample 2:
$model = User::find()
->joinWith('comments')
->orderBy('tbl_comments_id.id, tbl_user.id')
->all();
innerJoinWith()
$model = User::find()
->innerJoinWith('comments', false)
->all();
// equivalent to the above
$model = User::find()
->joinWith('comments', false, 'INNER JOIN')
->all();
Join()
JOIN_TYPE = INNER JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL OUTER JOIN etc
Syntax
$query = new Query;
$query ->select(['SELECT COLUMNS'])
->from('TABLE_NAME_1')
->join( 'JOIN_TYPE',
'TABLE_NAME_2',
'TABLE_NAME_2.COLUMN =TABLE_NAME_1.COLUMN'
);
$command = $query->createCommand();
$data = $command->queryAll();
Sample 1:
$query = new Query;
$query ->select([
'tbl_user.username AS name',
'tbl_category.categoryname as Category',
'tbl_document.documentname']
)
->from('tbl_user')
->join('LEFT OUTER JOIN', 'tbl_category',
'tbl_category.createdby =tbl_user.userid')
->join('LEFT OUTER JOIN', 'tbl_document',
'tbl_category.cid =tbl_document.did')
->LIMIT(5) ;
$command = $query->createCommand();
$data = $command->queryAll();
Output Query
SELECT `tbl_user`.`username` AS `name`, `tbl_category`.`categoryname` AS `Category`
FROM `tbl_user`
LEFT OUTER JOIN `tbl_category` ON tbl_category.createdby =tbl_user.userid
LEFT OUTER JOIN `tbl_document` ON tbl_category.cid =tbl_document.did
LIMIT 5
leftJoin()
Sample 1:
$query = new Query;
$query ->select(['tbl_user.username AS name', 'tbl_category.type as Category'])
->from('tbl_user')
->leftJoin('tbl_category', 'tbl_category.createdby = tbl_user.userid')
->limit(2);
$command = $query->createCommand();
$data = $command->queryAll();
Output Query
SELECT `tbl_user`.`username` AS `name`, `tbl_category`.`type` AS `Category`
FROM `tbl_user`
LEFT JOIN `tbl_category` ON tbl_category.createdby = tbl_user.useridd
LIMIT 2
use createcommand() method:
use yii\db\Query();
$connection = \Yii::$app->db;
$query = new Query;
$insql = $connection->createCommand("SELECT* FROM inventory );
$result=$insql->queryAll();
the above method list all data from the inventory table.
How to write my sql query in laravel 5.2, query is giving below
SELECT a.groupID, count( * ) AS totalCount, b.description
FROM devicelist AS a, devicegroup AS b
WHERE a.groupID = b.groupID
GROUP BY a.groupID
Try:
$query = DB::table('devicelist as a')
->join('devicegroup as b', 'a.groupID', '=', 'b.groupID')
->select(DB::raw('count(*) as user_count, a.groupID, b.description'))
->groupBy('a.groupID')
->get();
How I can write this sql to doctrine query language (DQL)?
SELECT *
FROM service
WHERE service.id NOT IN (SELECT id_service FROM reclamation)
Thanks.
try use not exists:
SELECT *
FROM service
WHERE NOT Exists (SELECT 1 FROM reclamation WHERE id_service = service.id)
Try to do this,
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT s
FROM YourBundle:Service s
WHERE s.id NOT IN
( SELECT s.idService FROM YourBundle:Reclamation r )'
)->getResult();
If that deserves, you can use the old school way! native-sql-with-docrtine
see the link http://doctrine.readthedocs.org/en/latest/en/manual/dql-doctrine-query-language.html#subqueries
$q = Doctrine_Query::create()
->select('s')
->from('Service s')
->where('s.id NOT IN (SELECT id_service FROM reclamation)
->getQuery()
->getResult();
I need to count the number of items returned in the subquery. If I write the subquery how DQL - all good, but if I try to build a query via QueryBuilder - I get an error.
Subquery DQL:
$qb3 = $this->createQueryBuilder('c')
->select('COUNT(c.id)')
->where('c.id IN (SELECT cl.id FROM Acme\AppBundle\Entity\ClassC cl INNER JOIN Acme\AppBundle\Entity\ClassP p WHERE p.var1 = :var1 AND p.var2 = cl.id GROUP BY cl.id)')
->setParameter('var1', $var);
Subquery via QueryBuilder:
$qb = $this->createQueryBuilder('c');
$qb->select('COUNT(c.id)')
->where(
$qb->expr()->in(
'c.id',
$this->createQueryBuilder('cl')
->select('cl.id')
->innerJoin('Acme\AppBundle\Entity\ClassP', 'p')
->where('p.var1 = :var1')
->setParameter('var1', $var)
->andWhere('p.var2 = cl.id')
->groupBy('cl.id')
->getDQL()
)
);
Both versions return the same DQL.
Error:
screen
Try to move setParameter() to main level of query.
$qb = $this->createQueryBuilder('c');
$qb->select('COUNT(c.id)')
->where(
$qb->expr()->in(
'c.id',
$this->createQueryBuilder('cl')
->select('cl.id')
->innerJoin('Acme\AppBundle\Entity\ClassP', 'p')
->where('p.var1 = :var1')
->andWhere('p.var2 = cl.id')
->groupBy('cl.id')
->getDQL()
)
)
->setParameter('var1', $var);
How to do this query in Doctrine 2 QueryBuilder:
SELECT AVG(x.distance) avg_distance FROM (SELECT r.* FROM result r WHERE r.place_id = ? GROUP BY r.place_id ORDER BY r.id DESC LIMIT 100
I try this:
$dql = $qb
->select('r.*')
->from('CoreBundle:Result', 'r')
->where('r.place = :place')
->orderBy('r.id', 'DESC')
->setMaxResults(100)
->setParameter('place', $place)
->getDQL()
;
$result = $qb
->select('AVG(x.distance) avg_distance')
->from($dql, 'x')
->getQuery()
->getArrayResult();
but not work
SELECT r.* FROM': Error: Class 'SELECT' is not defined.
$sql = "SELECT AVG(x.distance) avg_distance FROM (SELECT r.* FROM result r WHERE r.place_id = :place_id ORDER BY r.id DESC LIMIT 100) x ";
$stmt = $this->em->getConnection()->prepare($sql);
$stmt->bindValue(':place_id', $place->getId());
$stmt->execute();
return $stmt->fetch();