ManytoMany Entities Select Query Doctrine - php

I am trying to run a query. I have two many to many entities.
My query for these both entities below
$query = $user->createQueryBuilder('u')
->join('u.products', ua')
->Where('ua.id In (:uproducts)')
->setParameters(array(
'uproducts' => $userproducts ))
->getQuery();
$query = $user->createQueryBuilder('u')
->join('u.price,'up')
->Where('up.id In (:uprice)')
->setParameters(array(
'uprice'=>$userprice))
->getQuery();
If i do that in two queries like that it works. But I want that in 1 select query. Is there any idea how I could do that?
Thanks in advance.

Try this :
$query = $user->createQueryBuilder('u')
->join('u.products', 'ua')
->join('u.price,'up')
->Where('ua.id In :uproducts')
->andWhere('up.id In :uprice')
->setParameters(
array (
'uproducts' => $userproducts,
'uprice'=>$userprice
)
)
->getQuery();

Related

Using Laravel Eloquent's with() function along with inner join

I encountered a problem when trying to use with() function along with join:
$query = Model::query()->with([
'relationOne',
'relationTwo',
...
]);
$query->join(DB::raw("(
select *
from <models_table>
where <some_condition>
) as new_model"), 'new_model.id', '=', '<models_table>.id');
$query->paginate($rpp);
After paginate($rpp) call I received all items with appropriate relations appended, but without joined table (aka new_model). Is there a way to retrieve new_model along with relations ?
Have you tried to add select statement to emphasize the tables you want to get?
$query->join(DB::raw("(
select *
from <models_table>
where <some_condition>
) as new_model"), 'new_model.id', '=', '<models_table>.id')
->select(['<models_table>.*', 'new_model.*']);
Please try the below code hope it will help you.
$query = Model::query()->with([
'relationOne',
'relationTwo',
...
])
$query = $query->join(DB::raw("(
select *
from <models_table>
where <some_condition>
) as new_model"), 'new_model.id', '=', '<models_table>.id')
$query = $query->paginate($rpp);

Doctrine QueryBuilder from with subquery

I need to write some complex query builder expression. The sql looks like:
SELECT query,popularity,nb_words
FROM gemini_suggestion
WHERE query IN
(
SELECT * FROM
(
SELECT query
FROM gemini_suggestion
GROUP BY query
HAVING COUNT(query) > 1
) AS subquery
);
The code im stucked at is:
$queryBuilder = $em->createQueryBuilder();
$queryBuilder->select('a')
->from($this->entity['class'], 'a')
->where($queryBuilder->expr()->In('a.query', $subQuery->getDQL()));
$subQuery2 = $em->createQueryBuilder()
->select('b.query')
->from($this->entity['class'], 'b')
->groupBy('b.query')
->having('count(b.query)>1')
;
$subQuery = $em->createQueryBuilder();
$subQuery->select('a')
->from(...)
;
Any help would be nice!
You can try something like this. I'm assuming you have a namespace Entities where you have all your entities classes.
// Subquery to get the queries greater than 1
$subQueryBuilder = $this->entityManager->createQueryBuilder();
$subQueryBuilder->select('gemini_suggestion.query')
->from('Entities\gemini_suggestion', 'gemini_suggestion')
->groupBy('gemini_suggestion.query')
->having($subQueryBuilder->expr()->gt('COUNT(gemini_suggestion.query)', 1));
// Main query where you use the subquery to filter out the records you want
$queryBuilder = $this->entityManager->createQueryBuilder();
$queryBuilder->select('query, popularity, nb_words')
->from('Entities\gemini_suggestion', 'gemini_suggestion')
->where($queryBuilder->expr()->in('gemini_suggestion.query', $subQueryBuilder->getDQL()));
$result = $queryBuilder->getQuery()->getResult();
return $result;

Sql/Doctrine query to find data with multiple condition with Many to Many associations

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

subquery in andFilterWhere in yii2

I have to execute this query
select count(id) as numberofcompanies, sum(offered_value) as total_offered_value from campaign_comapany
where ( campaign_id in (select id from campaing where user_id = current_user ) or campaing_company.sp_user_id = current_user)
and campaign_company.status = '3'
And I wrote the query like this in yii2-
$query->select(['count(id) as numberofcompanies','sum(offered_value) as total_offered_value'])
->from('campaign_company')
->andFilterWhere(['or',['in','campaign_id',(new yii\db\Query())->select(['id'])->from('campaign')->where(['=','user_id',Yii::$app->user->id])],['=','campaign_company.sp_user_id',Yii::$app->user->id]])
->andWhere(['=','status','3'])
->one();
But it gives me error with unknow column campaign_company.user_id
but working if I just use where like following-
$query->select(['count(id) as numberofcompanies','sum(offered_value) as total_offered_value'])
->from('campaign_company')
->where(['in','campaign_id',(new yii\db\Query())->select(['id'])->from('campaign')->where(['=','user_id',Yii::$app->user->id])])
->andWhere(['=','status','3'])
->one();
What should I do to get the result mentioned sql query, I don't want to hit database server two time, thanks in advance
Use join:
$query->select(['count(id) as numberofcompanies','sum(offered_value) as total_offered_value'])
->from('campaign_company')
->innerJoin('campaign','`campaign`.`id` = `campaign_company`.`campaign_id`')
->where([
['=','campaign.user_id',Yii::$app->user->id])],
['=','campaign.campaign_company.sp_user_id',Yii::$app->user->id],
['=','campaign_company.status','3']
]
->one();
As is it is difficult to follow your logic. To simplify your code and your query, add the first condition as plain sql. Also since the second condition is required, you can swap the positions as follows:
$query
->select(['count(id) as numberofcompanies','sum(offered_value) as total_offered_value'])
->from('campaign_company')
->where(['status' => '3'])
->andWhere(['
campaign_id in (select id from campaign where user_id = :current_user )
or campaign_company.sp_user_id = :current_user1',
[':current_user' => Yii::$app->user->id, ':current_user1' => Yii::$app->user->id]])
->one();

how can i pass array in where clause with codeigniter?

How can I pass an array variable in where clause with codeigniter?
For example with a SQL query like:
Select(" item,price Where(userid=123 and proid=3 or userid=124 and proid=3... [upto n user id]userid=nth_id and proid=3");
If userid is stored in an array variable then how can I create such a condition in codeigniter?
I you are looking for this, it should look for a userid that is in the array and also has a proid of 3. I have not tested it but let us know how you get on.
$array = array( '123', '124' );
$this->db
->select( 'item, price' )
->from( 'table')
->where( 'proid', '3' )
->where_in( 'userid', $array )
->get();
$result = $query->result();

Categories