I have written a custom query in a repository:
public function findProductDetails($filter = array(), $offset = 0, $limit = 0)
{
$query = $this->getEntityManager()
->createQuery('SELECT prod, comp, cat FROM PaulDemoBundle:Product prod JOIN prod.category cat JOIN prod.company comp WHERE prod.productName LIKE \'%'.$filter['freetext'].'%\' ');
$query->setFirstResult($offset);
$query->setMaxResults($limit);
return $query->getResult();
}
Now I am trying to add an ORDER BY into it, using the orderBy() part of the Doctrine Query Builder:
$query->orderBy('prod.productRef', 'ASC');
But I get errors when trying to run this:
Call to undefined method Doctrine\ORM\Query::orderBy()
So I added the following to the top of my repository, underneath the USE call for EntityRepository:
use Doctrine\ORM\Query;
But, no dice.
All documentation I have found simply shows the query being built using the $query->orderBy() method. No where in the Symfony2 documentation does it say how to set up your repo to work with the Doctrine Query Builder.
How on earth do I add the orderBy() method?
Am I even constructing my query properly? (Its based on the Symfony2 docs, but they are pretty poor tbh)
If you are not using the queryBuilder, you cannot use the methods applied to it. Either you do your query on your own, adding the ORDER BY to your Query like this:
->createQuery('SELECT prod, comp, cat FROM PaulDemoBundle:Product prod JOIN prod.category cat JOIN prod.company comp WHERE prod.productName LIKE \'%'.$filter['freetext'].'%\' ORDER BY prod.productRef ASC');
or you build your Query with the QueryBuilder:
$qb = $em->createQueryBuilder();
...
See here for the QueryBuilder and here for differences on createQuery and QueryBuilder.
If you use the QueryBuilder, the right method is addOrderBy
Related
Laravel Framework - using version 5.4: If I used raw query as shown below in User.php controller and making paginate(3) as shown below. But it is giving error as "Call to a member function paginate() on array". solution please.
DB::select("select u.email,u.name,u.created_at from users u where u.id in (select max(ui.id) from users ui where ui.status = 0) order by ui.id desc")->paginate(3);
This code will do the job
DB::table('users as u')->select(['u.email','u.name','u.created_at'])->whereRaw("u.id in (select max(ui.id) from users ui where ui.status = 0)")->orderBy("ui.id","desc")->paginate(3);
yeah because your query ain't returning an object its returning an array. Try to use laravel query builder or Eloquent.
$users = DB::table('users')->paginate(15); //query builder example
$users = User::where('votes', '>', 100)->paginate(15); //eloquent example
Also make sure your query is working fine.
I'm quite a beginner at Symfony 2 and Doctrine 2. I have two models a Blog post and Comment. They are related to each other by blog_id FK inside comment table.
I just want to create a simple method that takes a blog id, Retrieves that blog and related comments. Instead of doing another query in lazy-loading the related comments.
Here's what i tried :
<?php
namespace Blogger\BlogBundle\Entity\Repository;
use Doctrine\ORM\EntityRepository;
class BlogRepository extends EntityRepository
{
public function getBlogWithComments($id)
{
$query = $this->getEntityManager()->createQuery('
SELECT b, c
FROM BloggerBlogBundle:Blog b
WHERE b.id = :id
JOIN b.id c
WHERE b.id = c.blog');
$query->setParameter("id", $id);
return $query->getResult();
}
}
I'm really a beginner at Doctrine 2. I usually use Query Builder, But i have no idea how to make a join using it. So Tried it in DQL, Couldn't figure it out either.
It gives me this syntax error whenever i try to call getBlogWithComments method:
[Syntax Error] line 0, col 80: Error: Expected end of string, got
'JOIN'
All what i want to know is that, How to write JOIN statements using Query Builder and DQL ? Knowing that documentation is not that helpful unfortunately.
A JOIN with DQL is done by referencing the relationship between the entities and it only needs to go one way. What I mean is b.comment c is all that is needed, there is no need for referencing c.blog.
public function getBlogWithComments($id)
{
return $this->getEntityManager()
->createQuery('
SELECT b, c
FROM BloggerBlogBundle:Blog b
JOIN b.comment c
WHERE b.id = :id
')
->setParameter("id", $id)
->getResult();
}
I have read the documentation but I can't quite figure out how to run the following query in Laravel 4
SELECT
COUNT(*)
FROM
acl a,
routes r
WHERE
(a.user_id = 1 OR
a.group_id IN(SELECT group_id FROM user_group_junction WHERE user_id = 1)) AND
r.route = 'protected' AND
a.routes_id = r.id;
So how would I run the query in Laravel 4 using eloquent?
Yes each table has a model and relationships are defined
Based on my selected answer the following is what I came up with (And works)
Acls::join('routes','routes.id','=','acl.routes_id')
->where('routes.route','=','protected')
->Where(function($in_parenthesis) use($user_id){
$in_parenthesis->whereIn('acl.group_id',function($where_in) use($user_id){
$where_in->select('group_id')
->from('user_group_junction')
->where('user_id','=',$user_id);
})
->orWhere('acl.user_id','=',$user_id);
})
->count();
Methods called on Eloquent models pass through to the Illuminate\Database\Eloquent\Builder class, which itself extends from the Illuminate\Database\Query\Builder class. This means that all the things you can do with the query builder, you can also do with Eloquent models. The exception being that you don't need to define the table.
So for example if you wanted to perform a join and a where like you've done above, you would just do:
$query = Acl::join('routes', 'acl.routes_id', '=', 'routes.id')
->where('routes.route', '=', 'protected');
$results = $query->get();
Obviously this isn't your whole query, but you can figure out the rest.
So I came to a point where I needed to create a custom query in my Entity Repository to do a sub-select.
The query itself seems sound and does indeed find the result I am after (I checked by running the query in Navicat) however, when trying to view the results (using Twig templates) I am getting the following error:
Item "id" for "Array" does not exist in DEMODemoBundle:Staff/Company:company.html.twig at line 42
Line 42 in that template is:
<td>{{ entity.id }}</td>
Previously, I was using a basic "findAll" query in my controller, and the Twig template worked fine (it uses a for loop to go through the results and print out a table)
So, I was under the assumption that if my custom query fetched a list of results, with all the same columns (just 1 added extra in the sub-select, not the ID mentioned though) then everything should be fine!
But clearly not. It seems as though there is another Array level for some reason and I am unsure as to why?
Here is my custom query in the repo (it does a sub select to create a parent_name column):
public function getCompanyWithParent()
{
$dql = 'SELECT c, (SELECT p.name FROM DEMO\DemoBundle\Entity\User\Company p WHERE p.id = c.parent) as parent_name FROM DEMO\DemoBundle\Entity\User\Company c';
$query = $this->getEntityManager()->createQuery($dql);
return $query->getArrayResult();
}
I have tried both:
return $query->getArrayResult();
and
return $query->getResult();
But to no avail.
Any ideas folks?
Sorted it. Seems I had to specify the columns I wanted to pull through e.g. SELECT c.id, c.name ..., and sadly couldn't just use SELECT c, ... FROM ...
I am attempting to pull a list of users using doctrine, with a join, from my database. I have the following function in my model:
public function getAttendees() {
$q = Doctrine_Query::create()
->select('a.id, a.name, a.url, m.id')
->from('Attendees a')
->leftJoin('a.Meetings m WITH m.Meeting_Slot_ID = ?', $this->getId());
return $q->execute();
}
I've checked the SQL generated by this query, and it is gabbing all the data I want. I am now trying to access the data retrieved. I have the following working:
foreach($object0>getAttendees() as $attendee){
echo $attendee->getName();
}
However, I can't figure out how to access the m.id field.
I think you can do this:
$attendee->getMeetings()->getId()
You have to use the alias you defined in your schema.yml (if you are using symfony)
Generally Doctrine uses this way to chain related models together:
model1->model2->model3
...->getModel2()->getModel3()->getModel3Field()
$attendee->getMeeting()->getId(); OR soemthing to that effect depending on how you have your relations/properties named.