My query is this :
$q = Doctrine_Query::create()
->from('plans p')
->whereIn('c.centerid',$centers)
->andWhere('p.agecategory = ?', $ageType)
->andWhere('p.type = ?', '2')
->andWhere('p.active = ?', '1')
->leftJoin('p.plansCenters c');
return $q->execute();
I wont to add one more row :
orWhere('p.allcenters =?' , '1')
Problem is this :
I wont to remove this whereIn clouse if c.allcenters =? 1 and oposit if c.allcenters =? 0 to show query whit whereIn clouse. If i wrhite orWhere after WhereIn clouse this 3 andWhere after this dont work Please help :)
I didn't fully understand the problem but I am familiar with complex orWhere/andWhere clauses. You have to use combined where conditions likes this:
->where("q.column=? AND w.column=?", ...)
->orWhere("e.id=? AND r.name=?", ....)
->orWhere("t.id=? AND (y.id=? OR u.id=?)", ...)
I hope you understand the idea, this is perfectly legit way.
Related
I'm struggling a bit with this code to get the count result from book_listing (totally) which is the total count of bookings. From the result, some are correct but some are multiplied by 3 or so.
Here is my code:
$this->db->where('list_status', 1)
->where('list_date >=', date('Y-m-d'))
->order_by("user_listings.list_created", "desc")
->limit(18, null)
->select('*, COUNT(user_bookings.book_listing) as totally')
->from('user_listings')
->join('user_images', 'user_images.img_listing = user_listings.list_reference')
->join('user_states', 'user_states.state_id = user_listings.list_state')
->join('user_bookings', 'user_bookings.book_listing = user_listings.list_reference', 'left')
->group_by('user_listings.list_reference')
->get();
Thanks to any help :)
So I solved it, the user_images table seems to be causing the issue due to multiple images being fetched while I need it to return only one.
$this->db->where('list_status', 1)
->where('list_date >=', date('Y-m-d'))
->order_by("user_listings.list_created", "desc")
->limit(18, null)
->select('user_listings.*,image.*,user_states.*')
->select('COUNT(user_bookings.book_listing) as totalBooked')
->from('user_listings')
->join('user_bookings', 'user_bookings.book_listing = user_listings.list_reference', 'left')
->join('(SELECT * FROM user_images WHERE user_images.img_key IN(SELECT MIN(user_images.img_key) FROM user_images GROUP BY user_images.img_listing)) AS image',
'image.img_listing = user_listings.list_reference')
->join('user_states', 'user_states.state_id = user_listings.list_state')
->group_by('user_listings.list_reference')
->get();
Basically, I had to do a select from the join table for user_images. Hope it helps someone else :)
The code is in EventUserTypes model
$this->find()
->select(['event_usertypes.user_type_id' , 'usertypes.name'])
->leftJoin('usertypes' , 'event_usertypes.user_type_id = usertypes.id')
->where(['event_usertypes.event_id'=>$event_id])
->all()
There is no error exept that it is only returning the columns of first table
and not the joined table. Its been 2 hours and have waisted too much energy on what is going wrong ? Any idea ?
If I select * then it returns all columns of first table
and if do this
select(['event_usertypes.user_type_id' , 'usertypes.name'])
it only returns event_usertypes.user_type_id not the name from the joined table
Please help me out
Try doing a direct DB query, to ensure that the usertypes table will be available in your query results:
$query = new \yii\db\Query;
$query->select(['e.user_type_id', 'u.name'])
->from('event_usertypes e')
->leftJoin('usertypes u', 'e.user_type_id = u.id')
->where(['e.event_id'=> $event_id]);
$command = $query->createCommand();
$resp = $command->queryAll();
Have a look at this SO question which was similar to yours. Also here is a link to the Yii documentation, in case this might help.
Please try like this
$query = new \yii\db\Query;
$query->select(['event_usertypes.user_type_id' , 'usertypes.name'])
->from('event_usertypes')
->leftJoin('usertypes' , 'event_usertypes.user_type_id = usertypes.id')
->where(['event_id'=> $event_id])->all();
$query->createCommand();
I have a simple Person tree with parent_id.
I wont to build a (Yii2) query to find all children of a given Person, that are parent of someone else (a.k.a not leaves).
The output SQL should looks like this:
select * from person t
where exists (select 1 from person p2 where t.id = p2.parent_id);
But cant find the right way to build this with the query builder, there is a method ->exists(), but not much documentation/examples about it.
Not sure if i understood correctly, but do you look something like this.
$subQuery = (new \yii\db\Query)
->select([new \yii\db\Expression('1')])
->from('person p2')
->where('t.id = p2.parent_id');
$query = (new \yii\db\Query())
->select('*')
->from('person t')
->where(['exists', $subQuery]);
$command = $query->createCommand();
print_r ($command->sql);
Generates sql like:
SELECT * FROM `person` `t` WHERE EXISTS (SELECT 1 FROM `person` `p2` WHERE t.id = p2.parent_id)
You should try something like :
$tableName = Person::tableName();
$subQuery = (new Query())->select('*')->from($tableName . ' t2')->where('t1.id=t2.parent_id');
$persons = Person::find()->from($tableName . ' t1')->where(['exists', $subQuery])->all();
http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html#where
I don't know the right way with only queries, but if you use PHP also, then I think this will help you.
And also try to search in Google with keywords: hierarchical menu PHP
I'm working on a school project and I'm trying to get a query working.
SELECT *
FROM `ziekmeldingen` AS a
WHERE NOT EXISTS
(SELECT *
FROM `ziekmeldingen` AS b
WHERE `ziek` = 1
AND a.personell_id = b.personell_id)
Name of the model: ZiekmeldingenModel
I tried 2 things, both dont work ->
$medewerkers = ZiekmeldingenModel::whereNotExists(function($query)
{
$query->select()->from('ziekmeldingen AS b')->where('ziek', '=', '1')->where('ziekmeldingen.personell_id', '=', 'b.personell_id');
})->get();
return $medewerkers;
And
$medewerkers = ZiekmeldingenModel::raw('SELECT * FROM `ziekmeldingen` as a WHERE NOT EXISTS ( SELECT * FROM `ziekmeldingen` as b WHERE `ziek` = 1 AND a.personell_id = b.personell_id)')->get();
Both of them give back all the results from the table while it should only give back 1 result (I've tested the original query, it works).
EDIT: Forgot to mention I'm using relationships in the model. So the raw solution probably won't work anyway
Found the answer. Had to use a combo of both the things I tried.
$medewerkers = ZiekmeldingenModel::select()
->from(DB::raw('`ziekmeldingen` AS a'))
->whereNotExists(function($query){
$query->select()
->from(DB::raw('`ziekmeldingen` AS b'))
->whereRaw('`ziek` = 1 AND a.personell_id = b.personell_id');
})->get();
return $medewerkers;
Thanks for any help and effort.
Definitely no need for select(). Also no raw in from or whereRaw needed.
The only unusual thing here is raw piece in the where, since you don't want table.field to be bound and treated as string. Also, you can use whereRaw for the whole clause in case you have your tables prefixed, otherwise you would end up with something like DB_PREFIX_a.personell_id, so obviously wrong.
This is how you do it:
$medewerkers = ZiekmeldingenModel::from('ziekmeldingen AS a')
->whereNotExists(function ($q) {
$q->from('ziekmeldingen AS b')
->where('ziek', 1)
->where('a.personell_id', DB::raw('b.personell_id'))
// or:
// ->whereRaw('a.personell_id = b.personell_id');
})->get();
Use the take() method though if you're not ordering your results the record you get back could be any of the results.
$medewerkers = ZiekmeldingenModel::raw('SELECT * FROM `ziekmeldingen` as a WHERE NOT EXISTS ( SELECT * FROM `ziekmeldingen` as b WHERE `ziek` = 1 AND a.personell_id = b.personell_id)')->take(1)->get();
I am trying to select ids and pass it into update by using this
$query = $this->db->query("SELECT GROUP_CONCAT(a.sponsor_id) as sponstr FROM (select sponsor_id from sponsor WHERE (pay_success = 'yes')AND (end_date_time > NOW()) and ((country_id = 1 and state_id = 24) or city_id = 123)
order by rand() limit 0,10) a");
if($query->num_rows()>0)
{
foreach($query->result() as $sponsorids)
{
$data['se_count'] = 0;
$this->db->where_in('sponsor_id',$sponsorids->sponstr);
$this->db->update('sponsor',$data);
}
}
but all the ids does not update, only the first one does.
the where_in produces the code below
WHERE sponsor_id IN ('5,4,2,3,1')
which i think it should be
WHERE sponsor_id IN (5,4,2,3,1)
Am I missing anything here or am I doing anything wrong which obviously I know I am. Please help
You should pass an array there. So pass not $sponsorids->sponstr but explode(',', $sponsorids->sponstr)
Also it's seems like a bad DB design decision, take some time and have a look on many-to-many concept