Until now I have been using a SQL query in yii2 which was working fine locally but as soon as I deploy it to the server it shows
I have tried changing it to yii query since its a proper implementation below
$query = $connection->createCommand("SELECT a.name_of_flight, a.time_of_flight, (a.no_of_passenger - b.cnt) as avail, a.no_of_passenger FROM flight_schedule a LEFT JOIN (SELECT flight_time, COUNT(id) AS cnt FROM book_eticket WHERE flight_date='$date' AND company_name = '$comp_name' GROUP BY flight_time) b ON a.id = b.flight_time")->queryAll();
to
$query = (new \yii\db\Query());
$query
->select('a.name_of_flight, a.time_of_flight, (a.no_of_passenger - b.cnt) as avail, a.no_of_passenger')
->from('flight_schedule a')
->leftJoin('flight_time', ('COUNT(id) AS cnt FROM book_eticket'))
->where(array('and', 'flight_date=2016-6-29', 'company_name = Team5'))
->groupBy(['flight_time b','ON a.id = b.flight_time']);
$command = $query->createCommand();
$query = $command->queryAll();
but I get an error:
Can anybody help me find out the problem? Thanks in advance
First screen says about access issues. Second - that operands like date and team is not string. That is wrong. Can you quote them?
Related
I need to write this query with Doctrine. How can I write it down using QueryBuilder?
SELECT charges.id, charges.currency, charges.total_transactions,
charges.total_volume, charges.commission, refunds.total_payouts
FROM
(SELECT ...very long query...) charges
LEFT JOIN
(SELECT ...very long query...) refunds
ON charges.id = refunds.id AND charges.currency = refunds.currency
You can use Native SQL and map results to entities:
use Doctrine\ORM\Query\ResultSetMapping;
$rsm = new ResultSetMapping;
$rsm->addEntityResult('AppBundle:Charges', 'charges')
->addEntityResult('AppBundle:Refunds', 'refunds')
->addFieldResult('charges', 'id', 'id')
->addFieldResult('charges', 'currency', 'currency')
->addFieldResult('charges', 'total_transactions', 'total_transactions')
->addFieldResult('charges', 'total_volume', 'total_volume')
->addFieldResult('charges', 'commission', 'commission')
->addFieldResult('refunds', 'total_payouts', 'total_payouts')
;
$sql = "
SELECT
charges.id,
charges.currency,
charges.total_transactions,
charges.total_volume,
charges.commission,
refunds.total_payouts
FROM
(SELECT ...very long query...) charges
LEFT JOIN
(SELECT ...very long query...) refunds ON charges.id = refunds.id AND charges.currency = refunds.currency
WHERE some_field = ?
";
$query = $this->getEntityManager()->createNativeQuery($sql, $rsm);
$query->setParameter(1, $name);
$entities = $query->getResult();
You can use DQL like this:
$dql = "SELECT ...";
$q = $entityManager->createQuery($dql)->setParameters($arrayParameters);
$result = $q->execute();
or QueryBuilder for each sub-query, like:
// subquery 1
$subQuery1 = $entityManager->createQueryBuilder()
->select('...')
->from('...')
->getDQL()
;
// subquery 2
$subQuery2 = ...
// etc
// ...
// main query
$query = $entityManager->createQueryBuilder()
->select('...')
->from('...', $subQuery1)
->leftJoin('...', $subQuery1->getDQL()),
->where()
;
PS: I just try provide gist for you... hope now you have clue...
Now I found out that it's impossible.
Comment created by stof:
DQL is about querying objects. Supporting subselects in the FROM clause means that the DQL parser is not able to build the result set mapping anymore (as the fields returned by the subquery may not match the object anymore).
This is why it cannot be supported (supporting it only for the case you run the query without the hydration is a no-go IMO as it would mean that the query parsing needs to be dependant of the execution mode).
In your case, the best solution is probably to run a SQL query instead (as you are getting a scalar, you don't need the ORM hydration anyway)
Source: https://github.com/doctrine/doctrine2/issues/3542
The code is in EventUserTypes model
$this->find()
->select(['event_usertypes.user_type_id' , 'usertypes.name'])
->leftJoin('usertypes' , 'event_usertypes.user_type_id = usertypes.id')
->where(['event_usertypes.event_id'=>$event_id])
->all()
There is no error exept that it is only returning the columns of first table
and not the joined table. Its been 2 hours and have waisted too much energy on what is going wrong ? Any idea ?
If I select * then it returns all columns of first table
and if do this
select(['event_usertypes.user_type_id' , 'usertypes.name'])
it only returns event_usertypes.user_type_id not the name from the joined table
Please help me out
Try doing a direct DB query, to ensure that the usertypes table will be available in your query results:
$query = new \yii\db\Query;
$query->select(['e.user_type_id', 'u.name'])
->from('event_usertypes e')
->leftJoin('usertypes u', 'e.user_type_id = u.id')
->where(['e.event_id'=> $event_id]);
$command = $query->createCommand();
$resp = $command->queryAll();
Have a look at this SO question which was similar to yours. Also here is a link to the Yii documentation, in case this might help.
Please try like this
$query = new \yii\db\Query;
$query->select(['event_usertypes.user_type_id' , 'usertypes.name'])
->from('event_usertypes')
->leftJoin('usertypes' , 'event_usertypes.user_type_id = usertypes.id')
->where(['event_id'=> $event_id])->all();
$query->createCommand();
I have a simple Person tree with parent_id.
I wont to build a (Yii2) query to find all children of a given Person, that are parent of someone else (a.k.a not leaves).
The output SQL should looks like this:
select * from person t
where exists (select 1 from person p2 where t.id = p2.parent_id);
But cant find the right way to build this with the query builder, there is a method ->exists(), but not much documentation/examples about it.
Not sure if i understood correctly, but do you look something like this.
$subQuery = (new \yii\db\Query)
->select([new \yii\db\Expression('1')])
->from('person p2')
->where('t.id = p2.parent_id');
$query = (new \yii\db\Query())
->select('*')
->from('person t')
->where(['exists', $subQuery]);
$command = $query->createCommand();
print_r ($command->sql);
Generates sql like:
SELECT * FROM `person` `t` WHERE EXISTS (SELECT 1 FROM `person` `p2` WHERE t.id = p2.parent_id)
You should try something like :
$tableName = Person::tableName();
$subQuery = (new Query())->select('*')->from($tableName . ' t2')->where('t1.id=t2.parent_id');
$persons = Person::find()->from($tableName . ' t1')->where(['exists', $subQuery])->all();
http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html#where
I don't know the right way with only queries, but if you use PHP also, then I think this will help you.
And also try to search in Google with keywords: hierarchical menu PHP
Here is my doctrine query running code:
$queryString = "SELECT ct, count(ct.id), IDENTITY(a.service) "
. "FROM ConnectionTriple ct "
. "JOIN ct.account_connection ac "
. "JOIN Account a WITH (a = ac.account_1 OR a = ac.account_2) "
. "GROUP BY a.service, ct.property, ct.value";
$query = $em->createQuery($queryString);
//echo $query->getSQL();
$results = $query->getResult();
echo count($results);
This above code is returning 2 results(final two from below screenshot) instead of 4(expected). But, when I run the equivalent SQL(got by $query->getSQL()) on phpmyadmin, it returns expected 4 rows which is as below:
Equivalent SQL Query:
SELECT u0_.id AS id0, u0_.value AS value1, u0_.status AS status2, u0_.flag AS flag3, count(u0_.id) AS sclr4, u1_.service_id AS sclr5, u0_.property_id AS property_id6, u0_.account_connection_id AS account_connection_id7 FROM usc_connection_triple u0_ INNER JOIN usc_account_connection u2_ ON u0_.account_connection_id = u2_.id AND (u2_.status = 1) INNER JOIN usc_service_subscriber u1_ ON ((u1_.id = u2_.account_1_id OR u1_.id = u2_.account_2_id)) WHERE (u0_.status = 1) AND (u1_.status = 1) GROUP BY u1_.service_id, u0_.property_id, u0_.value
PHPMyAdmin Result:
So, I guess, there is something wrong in result to object hydration by doctrine, I guess. Anyone has any idea why this might happen/possible solution?
My Doctrine version are:
"doctrine/dbal": "2.3.2",
"doctrine/orm": "2.3.2",
Update: I am certain about the hydration issue. Because, I tried with individual column retrieving and using scalar hydration:
$results = $query->getResult(\Doctrine\ORM\Query::HYDRATE_SCALAR);
This is returning perfectly. Which is expected number of rows, 4 and data as well.
I would say this is totally normal.
As you pointed it out, doctrine (default) hydration mode would represent the result set as an object graph.
An object graph always have a root object (in your case ConnectionTriple ct).
There are 2 ct in your result set (with id 1 and 2).
Doctrine object hydrator will be smart enough to return you and array
of 2 ConnectionTriple objects, each line containing the related data.
The scalar hydrator, howerver will simply return the raw resultset, without building a graph from it.
When I try the follow mysql query in send I just get back an empty results set (who suposed to be filled).
I tried the follow query in my mysql workbench (gives a results back)
SELECT `websites`.*, `s`.`website_id` AS `websites.id`
FROM `websites`
INNER JOIN `websites_statistics` AS `s` ON `s`.`website_id` = `websites`.`id`
WHERE `websites`.`website` = 'google.com' LIMIT 0,1
And this one in my ZF2 application (empty result set)
$sql = new Sql($this->tableGateway->getAdapter());
$select = $sql->select();
$select->from('websites')
->join(array('s' => 'websites_statistics'), 's.website_id = websites.id', array('websites.id' => 'website_id'), \Zend\Db\Sql\Select::JOIN_INNER)
->where(array('websites.website' => 'google.com'));
$resultSet = $this->tableGateway->selectWith($select);
echo $select->getSqlString();
return $resultSet;
Debug result:
SELECT "websites".*,
"s"."website_id" AS "websites.id"
FROM "websites"
INNER JOIN "websites_statistics" AS "s" ON "s"."website_id" = "websites"."id"
WHERE "websites"."website" = 'google.com'
(!updated) The query a bit so it's more easier. I think there goes something wrong at the first moment because I think "s"."website_id" AS "websites.id" has to flip in the other direction .. "websites.id" AS "s"."website_id" I need websites.id to take record by website_id from the websites_statistics table.
Thanks in advance!
Nick
I got it work. The problem wasn't the query it's self. I had to add the fields of the second table (to one I join) to the model (exchangeArray) of the first table! That did the trick. Thanks you all.