I have two entities Message and Skill, and many to many relationship between them. I am trying to get all messages with skill=5 or without any skills.
$queryBuilder = $repository->createQueryBuilder('entity');
$queryBuilder->leftJoin('entity.skills', 'skill');
$queryBuilder->andWhere(
$criteria->expr()->orX(
$criteria->expr()->eq('skill.id', 5),
$criteria->expr()->isNull('skill.id')
)
)
But in results I have question ONLY with skill=5.
How can I select questions without skill or with skill=5 is SINGLE query?
$queryBuilder = $repository->createQueryBuilder('entity');
$queryBuilder->leftJoin('entity.skills', 'skill');
$queryBuilder->where('skill.id = 5');
$queryBuilder->orWhere('skill.id IS NULL');
Related
I am implementing category filters with many to many relations in doctrine using symfony3. I have an entity Business and Category with many to many association. The new table with many to many relations looks like below
business_id category_id
1 1
1 2
2 1
2 2
3 1
Now I want to get all the businesses which are having category_id=1 and category_id=2.
It should select the business id 1,2.
My Sql Query:-
SELECT * FROM business
LEFT JOIN business_category ON business_category.business_id=business.id
WHERE business_category.category_id = 1 AND business_category.category_id = 2
Any SQL or Doctrine query would work.
I would really appreciate for any help.
To get the businesses which exists in both categories your write your query builder as follows,I assume your entities are mapped with proper many to many relationship
$repo = $this->getDoctrine()->getRepository('YourBundle:Business');
$repo = $this->createQueryBuilder('b')
->addSelect('COUNT(DISTINCT c.id) AS total_categories')
->innerJoin('b.categories', 'c');
$categoryIds = array(1,2);
$repo->add('where', $qb->expr()->in('c', $categoryIds))
->groupBy('b.id')
->having('total_categories = '.count($categoryIds))
->getQuery()
->getResult();
For reference see another answer here
you can try
$qb->select( 'p' )
->from( 'AppBundle:Project', 'p' )
->innerJoin( 'p.users', 'u' )
->where( 'u.id=:userIdDaily' )
->andWhere('u.id=:UserID')
->setParameter( 'userIdDaily', $UserObj )
->setParameter( 'UserID', $UserObj->getId() )
;
$query = $qb->getQuery();
$results = $query->getResult();
i have project and user many to many relation. i use this to fetch data with multiple where clauses
I'm facing some trouble getting my results with doctrine query builder, in a Symfony 2.8 app :
I've got here 3 entities :
Song
Artist
Category
All songs have at least 1 artist and 1 category
Song has manytomany relation with Artist, and manytomany with Category aswell
I would like to get the Songs entities having the same artists OR categories as one song given to this function :
public function findRelatedSongs($song)
{
$em = $this->getEntityManager();
$artistsIds = $this->getArtistsIds($song);
//returns a string like '1,2,3'
$categoriesIds = $this->getCategoriesIds($song);
//returns a string like '1,2,3'
$q = $em->getRepository("BeatAdvisorBundle\Entity\Song")
->createQueryBuilder('s')
->join('s.artists', 'a')
->join('s.categories', 'c')
->where('a.id in (:artistsIds)')
->orWhere('c.id in (:categoriesIds)')
->andWhere('s.id <> :songId')
->setParameter('artistsIds', $artistsIds)
->setParameter('categoriesIds', $categoriesIds)
->setParameter('songId', $song->getId())
->getQuery();
$sql = $q->getSql();
// here I can read the sql query generated
$result = $q->setMaxResults(16)
->getResult();
return $result;
}
It gives me back the related songs on same artists, but not on categories.
Is there a problem with the way I wrote this ?
If I copy and paste the sql query, setting the ids as parameters like something_id in (1,2) it works good...
EDIT
Now I know that song-A having only artist-x will match some songs having only artist-x ; same for categories. might be a problem of type (string VS int) causing problems with in(x,y) instead of in (x) ?...
As far as I know Doctrine uses DQL (Doctrine Query Language), not SQL. Expressions are a bit different sometimes. You can use the QueryBuilders Expression object to programmatically build your expressions.
$qb->where(
$qb->expr()->in('a.id', ':artistsIds'),
$qb->expr()->eq('s.id', ':songId')
);
Reference:
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html
OK, my error was to set my parameters as string (imploded arrays of ids).
I had to give the array of integers itself...
I have the following DQL:
$qb = $this->createQueryBuilder('p')
->select('PARTIAL p.{id, name}', 'p.sku', 'p.name', 'bu.abbreviation AS baseUnit', 'p.price',
'p.WP', 'p.SP', 'p.MP', 'p.PP', 'p.P3', 's.name as supplier')
->join('p.baseUnit', 'bu')
->join('p.suppliers', 's')
->where('p.active = 1');
Product has many suppliers and supplier can be in many products.
The problem in the query is that it returns only 1 supplier.
I tried searching the internet but it always has setParameter on it which i dont need since i just want to get all the products with their related suppliers only without any parameters or whatsoever.
How can I do that in DQL?
Thanks.
I have two tables Candidates & Qualifications with a joining pivot table called Results.
What I want to do is select all candidates for this centre and filter them by a value in the pivot table.
So select all candidates from centre 1 where the pivot “status” = “REGISTERED”
I have tried numerous approaches and am currently with the one below but nothing is working.
$candidates = Candidate::where('batch_centre_id','=', $id)->with(array('qualification' => function($q)
{
$q->wherePivot('status','=', 'REGISTERED');
}))->get();
Any advice would be much appreciated
In Eloquent wherePivot method can only be loaded on a relation. The way you're doing it, you're calling it on qualifications relation, therefore you're fetching all candidates and then, for each of them, you're loading qualifications that have status=REGISTERED. That's why you're getting all candidates.
You could work around it by using Eloquent's whereHas() method that let's you filter the base model you're trying to fetch by attributes of some relation. In your case the following should work:
$candidates = Candidate::where('batch_centre_id','=', $id)
->whereHas('qualifications', function($q) {
$q->wherePivot('status','=', 'REGISTERED');
})->with('qualifications')->get();
This way you'll get only candidates that have a qualification with status=REGISTERED and all their qualifications. If you want to additionally filter loaded qualifications by status, add the constraint like you did in your code:
$candidates = Candidate::where('batch_centre_id','=', $id)
->whereHas('qualifications', function($q) {
$q->wherePivot('status','=', 'REGISTERED');
})->with(array('qualifications', function($q) {
$q->wherePivot('status','=', 'REGISTERED');
})->get();
I've been trying with no success to user doctrine2 query builder to fetch records in a related many-to-many table using a where clause.
I would like to reproduce the following statement:
SELECT [...] FROM Company
JOIN CompanyAddress ON CompanyAddress.CompanyId = Company.Id
JOIN Address ON Address.Id = CompanyAddress.AddressId
WHERE Address.State = ?
following some ideias found on google, stackoverfow and doctrine docs:
$qb = $this->_em->createQueryBuilder();
$qb->select('c')
->from('Company', 'c')
->where(':State MEMBER OF c.Address')
->setParameter('State', $arguments);
but the results are not the desired one. Any help? Thanks..