I have the following query that uses an IN statement.
$ids = array(1,2,3);
$query = 'select o from Organisation o where o.id in (:ids)';
$this->_entityManager->createQuery($query)
->setParameter('ids', implode(', ', $ids))
Doctrine is not returning any results, I think it is because of something wrong in the conversion that Doctrine does for the passed parameter $ids which is an array.
How to make it work?
Try passing the array itself to ->setParameter(...) instead of imploding it into a string.
I used this (setParameter didn't seem to work for me):
$em->createQuery('SELECT users FROM Entities\User users WHERE users.id IN (:ids)')
->setParameters(array('ids' => $ids));
http://redbeardtechnologies.wordpress.com/2011/07/01/doctrine-2-dql-in-statement/
I solved this:
$con = $this->getEntityManager();
$query = $con->createQuery("SELECT cl
FROM BackendBundle:classifieds cl
INNER JOIN BackendBundle:locations lo WITH cl.locationId = lo.id
INNER JOIN BackendBundle:municipality mu WITH lo.municipalId = mu.id
WHERE cl.verified = false AND mu.id = ".$munId." AND cl.locationId NOT IN (:ids) ");
$query->setParameters(array('ids' => $locsIds));
return $query->getResult();
I'm struggling with the IN statement too, using the $query->expr()->in() construct...
Try:
$em->createQuery(“SELECT users FROM Entities\User users WHERE users.id IN (':ids')”)
->setParameters(array(‘ids’ => $ids));
I think the simple quotes around your parameters in the IN() part are necessary...
Related
I am getting error Illegal string offset 'order_status_id' when I want to get loop data in view
Here's the code:
controller.php
if (isset($_POST["email"])) {
$email = $_POST["email"];
}
$this->load->model('order/myorder');
$data['data1'] = $this->model_order_myorder->getOrder($email) ;
view.php
foreach ($data1 as $row) {
echo echo $row->order_id;
}
model.php
class ModelOrderMyorder extends Model {
public function getOrder($email) {
$sql = "SELECT * FROM ".DB_PREFIX."order, ".DB_PREFIX."order_product WHERE ".DB_PREFIX."order.email = '$email'";
$query = $this->db->query($sql);
return $query ;
}
}
Still not getting it showing Trying to get property of non-object in view.
First off, if you want to iterate through all the order products for a given email (which is what I think you want) you should change the getOrder() method to return:
return $query->rows;
Then in the controller you need to change:
$data['data1'] = $this->model_order_myorder->getOrder($email) ;
to
$this->data['data1'] = $this->model_order_myorder->getOrder($email);
Finally, in your view, you'll be accessing an array not an object so you should lose the extra echo (assuming this is a typo) and change:
echo echo $row->order_id;
and get the index as:
echo $row['order_id']
Also, in addition to the above, I'll suggest you utilize some of the methods and code conventions found in Opencart:
When accessing the $_POST global you can use the sanitized
version $this->request->post
Your query fails to backtick the order table which can result
in errors in you didn't set a prefix. And you are not escaping
$email which is a good idea for a number of reasons. Also, it makes
things easy if you give your tables an alias. Finally, a join on the
tables... so I might consider rewriting that query like this:
$sql = "SELECT * FROM `" . DB_PREFIX . "order` o LEFT JOIN " . DB_PREFIX . "order_product op USING (order_id) WHERE o.email = '" . $this->db->escape($email) . "'";
To be honest, I'm not sure what results you're expecting from that query but bear in mind that if there are multiple products for an given order you will end up with multiple rows returned.
Just a few tips.. hopefully this is useful to you.
I want to create a Doctrine Query: (Doctrine 2.3)
SELECT * FROM `car` WHERE `plate` like '%' AND (`datetime` BETWEEN '2013-03-13 22:20:18' AND '2013-03-13 22:20:20') OR (`datetime` BETWEEN '2013-03-13 15:10:18' AND '2013-03-13 15:10:16')
I tried the following but its not working:
$qry = $this->manager()->createQueryBuilder()
->from($this->entity, 'e')
->select('e');
$qry->where('e.plate like :plate');
$qry->setParameter('plate', $plate);
$qry->andWhere(
qry->expr()->between(
'e.datetime',
':dateFrom',
':dateTo'
)
)
->setParameter('dateFrom', $fromdate)
->setParameter('dateTo', $todate);
$qry->orWhere(
$qry->expr()->between(
'e.datetime',
':dateFrom',
':dateTo'
)
)
->setParameter('dateFrom1', $fromdate1)
->setParameter('dateTo1', $todate1);
OutPut of above query:
SELECT e FROM user e WHERE (e.plate like :plate AND (e.datetime BETWEEN :dateFrom AND :dateTo)) OR (e.datetime BETWEEN :dateFrom AND :dateTo)
I want to check two dates in same column how can I check? Is the syntax correct?
Currently It is like this:
(Plate AND (Date)) OR Date)
Case 1
But it should come like the following for good output.
(Plate) AND ((Date) OR (Date))
Case 2
In other case it should come like this:
((Plate) or (Plate)) AND ((Date) OR (Date))
Can some one help me I am not an expert in Doctrine I am a learner!
After some search and advice from many individual I finally found some logic and understood the expression in Doctrine. Below I have given all the expression with an example. Code to be tested.
$ex1 = $qry->expr()->like('e.user', "'".$user."'");
$ex2 = $qry->expr()->orX(
$qry->expr()->between('e.datetime', "'".$datetimefrom."'", "'".$datetimeto."'")
);
$ex3 = $qry->expr()->in('e.country', $country);
$final_expression = $qry->expr()->andX($ex1,$ex2,$ex3);
You can also refer the below issue and solution which helped me to solve the above Question by me.
REF Multiple Query in Doctrine with NAND,NOR,NOT,AND Operators
I tried to extract a specific data in a table but my code does work:
$db =& JFactory::getDBO();
$query = "SELECT * FROM #_contact_details WHERE user_id = 43;";
$db->setQuery($query);
$results = $db->loadObjectList();
$results = $results["name"];
results does not give anything.
anyone have an idea?
thank you in advance
The $result is an array of stdClass Object. If you want to access the value You've to use:
$results = $results[0]->name;
Hope this helps!
$results is not giving anything because loadObjectList() returns array of object so the result(structure) would be for one row similar to this-
print_r($results)
Array
(
[0] => stdClass Object
(
[name] => "test"
)
)
so you can read data like this $results = $results[0]->name;
You can read here
Hope this will help.
I made a moles in for testing my repository class and it works when I put DefaultIfEmpty(new Drivers()) but when I run the program, I get this error: Unsupported overload used for query operator 'DefaultIfEmpty'.
But when I put it back to DefaultIfEmpty(), it works fine but my*strong text* moles test now returns a null value.. Here is my code:
var result = from p in this.context.AirPositions
join a in this.context.Airplane p.airplane_id equals a.id
join s in this.context.Status on p.status_id equals s.id
join dp in this.context.DriversPositions on p.id equals dp.position_id into dpJoin
from ds in dpJoin.DefaultIfEmpty(new DriversPosition())
join d in this.context.Drivers on ds.driver_id equals d.id into dsJoin
from drs in dsJoin.DefaultIfEmpty(new Driver())
orderby p.timesent descending
select new PositionViewModel()
{ ... };
It seems like the linq provider does not support an overload on the DefaultOrEmpty function which takes a default value.
You have to rewrite your code to something else if you want to test this with moles. I know that test should not change your code. Try to rewrite your code by using SingleOrDefault.
It seems there is a problem with code that runs with Linq-to-Sql and Linq-to-Object.
I solved it with the following:
var result = from p in this.context.AirPositions
join a in this.context.Airplane on p.asset_id equals a.id
let driver = (from dd in this.context.DriversPositions.Where(u => u.position_id == p.id)
join d in this.context.Drivers on dd.driver_id equals d.id
select d).FirstOrDefault()
orderby p.timesent descending
select new PositionViewModel() {...}
Hope this helps other people :)
I have come across this multiple times in the past, and I just ended up writing a raw SQL query to overcome it, but I really want to find out why this is happening. Look at the statement below
$q = $this->entityManager->createQuery('SELECT um,s,st
FROM Dashboard\Entity\Metric um
JOIN um.stat st
JOIN um.site s
JOIN s.clients c
WHERE c.id = ?1
AND s.competitor = 0
AND s.ignored = 0
AND st.id IN (?2)
GROUP BY s.id, st.id
ORDER BY st.response_field, s.id')
->setParameter(1, $params['c_id'])
->setParameter(2, $statId);
$sql = $q->getSql();
$rs = $q->getResult();
If I take the contents of $sql and paste them into a mySQL tool and run the raw query, it returns 18 results which is correct.
However, $rs only contains 3 results. $statId is a comma-separated string of 6 numbers: (1,2,3,4,5,6). So I am grouping by st.id, and s.id. There will be 3 s.id elements for every st.id element, working out to the 18 results I expected. What's happening is Doctrine is only returning the first st.id which is the group of 3 s.id 's
Any idea what could be causing this?
I got my answer from IRC, but posting here in case it helps someone else. Smart WHERE IN statements aren't planned for support until 2.1 version.
http://groups.google.com/group/doctrine-dev/browse_thread/thread/fbf70837293676fb
But I can accomplish the same goal with query builder.
http://www.doctrine-project.org/docs/orm/2.0/en/reference/query-builder.html