Trying to join two simple tables using Doctrine 2 - php

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();
}

Related

How to convert given SQL query to Eloquent laravel?

I am bit struggling to convert below given SQL query to eloquent.
Here is an example of what I am trying to do -
SELECT u.wallet_address AS wallet_address, p.id AS project_id
FROM users u, projects p, investment_investor i
WHERE u.id = i.user_id AND
p.id=i.project_id AND
u.wallet_address <> '' AND
p.wallet_address <> '' AND
p.contract_address <> ''
GROUP BY u.id, p.id;
The below SQL query gives me the expected output, which I am able to build with the Laravel DB query builder. But want to standardise it to Laravel framework.
Your help is much appreciated!
First thing you need to have to be able to write queries in the laravel way is something called Model. Example of a model would be like so
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
//
}
You can read more about it here
Once you create it, you can start writing queries. For example
$results = Users::selectRaw('users.wallet_address as `wallet_address`,'.
'id as `project_id`')
->get();
You can read more about joins and other things here
$result=DB::table('investment_investor')
->select('users.wallet_address as wallet_address','projects.id AS project_id')
->join('users','users.id','=','investment_investor.user_id')
->join('projects','projects.id','=','investment_investor.project_id')
->where('users.wallet_address','!=','')
->where('projects.wallet_address','!=','')
->where('projects.contract_address','!=,'')
->groupBy('users.id', 'projects.id')
->get();

Issue with "where" in an associated query in Symfony 3

I'm trying to make a "search engine" for my app; the table I want to show, contains two fields which are associated to another tables.
I'm using this query:
Select work from WorkBundle:Work work
where work.client.name like '$search%'
Work, is associated with the tables "user" and "client", I have the associations correctly defined so I don't have to use the inner join statement, but I get the following error:
[Semantical Error] line 0, col 68 near 'nombre like 'fsdf%'': Error: Class WorkBundle\Entity\Work has no field or association named client.nombre
I don't know how to access to the "name" field which is on the "client" table.
Actually I can do the same by using a full inner join query and it works but I can't use it in my app.
I do not know for sure but it seems you cant use selectors like work.client.name. I think it based on doctrine uses "lazy" queries. So you must use table joins in this case.
So it should look smth like that
// work repository
public function findByKeyword($keyword)
{
$qb = $this->createQueryBuilder("w");
$result = $qb
->add('where', $qb->expr()->like("wc.name", ':keyword'))
->leftjoin("w.client", "wc") //or join or innerjoin depends of your case
->setParameters([
'keyword' => $keyword
])
->getQuery()
->getResult()
;
return $result;
}

How to run a query in Laravel 4 using eloquent

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.

Symfony2 - Custom Repository + Doctrine QueryBuilder = Errors?

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

Accessing Doctrine related field from JOIN

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.

Categories