How to do add a select into a where in ZF2? - php

First of all, hello there !=)
I was wondering if anyone knew how to write a select in a where such as
SELECT my_column
FROM my_table
WHERE field_1 = something
AND field_2 = ( SELECT field_2
FROM my_table_2
WHERE my_field = $myParam );
I know how to write this query without the select :
//This part shouldn't matter, it's just my way of connecting to table database
$select = $mytable1->getTableGateway()->getSQL()->select();
//This is where the fun begin
$select->colunms(array('my_column'))
->where(array('field_1' => 'something', 'field_2' => ??);
TRY 1 :
Using another variable that allows me to connect to the other base doesn't seem to work because of course it's not a array or anything...
$select_2 = $myTable2->tableGateway->getSQL()->select();
$select_2->colunms(array('field_2'))
->where(array('my_field' => $myParam);
$select->colunms(array('my_column'))
->where(array('field_1' => 'something', 'field_2' => $select_2);
I tried adding something like :
$var= $myTable2->getTableGateway()->selectWith($select_2);
//and then
$select->colunms(array('my_column'))
->where(array('field_1' => 'something', 'field_2' => $var->toArray());
It doesn't work either, because of course it's not one line...
I don't think a foreach is really necessary
Any thought before i go too far in my thoughts ?
Thank in advance

In ZF1 it works like this:
$select_2 = $myTable2->tableGateway->getSQL()->select();
$select_2->columns(array('field_2'))
->where(array('my_field = ?' => $myParam);
$select->columns(array('my_column'))
->where(array('field_1 = ?' => 'something', 'field_2 = ?' => $select_2)
Honestly, I'm not sure if it'll work in ZF2, but try to add the wildcard '?' to your where clause.
Best,

Related

Combining and and or operators in Phalcon\Mvc\Model\Criteria

I'm just writing my first phalcon application and have a question for filtering a query using Phalcon\Mvc\Model\Criteria.
Finally I want a query like this
SELECT *
FROM table
WHERE
status = 'A' AND
(
title LIKE 'combining%' OR
title LIKE 'phalcon%' OR
(
title LIKE 'criteria%' AND
title LIKE '%phalcon'
)
)
For me it seems there is no way for parenthesis in phalcons model criteria. The only way to achieve this is by writing phql.
Instead of writing a complete phql I maybe can write something like this, but that is getting the same complexity
<?php
$query = Table::query();
$query->where('status = :status:', array('status' => 'A'));
$query->andWhere('(
title LIKE :title1: OR
title LIKE :title2: OR (
title LIKE :title3: AND
title LIKE :title4:
)
)', array(
'title1' => 'combining%',
'title2' => 'phalcon%',
'title3' => 'criteria%',
'title4' => '%phalcon'
));
It looks like Criteria's "where", "andWhere" and "orWhere" methods will add the outer parenthesis for you, then you can manually write the inner parenthesis.
$query = Model::query()
->where('status = "A"')
->andWhere('title LIKE "combining%" OR
title LIKE "phalcon%" OR
(
title LIKE "criteria%" AND
title LIKE "%phalcon"
)
');
$models = $query->execute();
You can test that the where clause is correct.
var_dump($query->getWhere());

Cakephp, change query to fetch all in one

I have multiple query in foreach i know its wrong and i want to correct it i have virtual_fields like this:
'night_hours' => 'SUM(Hour.night)',
'half_hours' => 'SUM(Hour.half)',
'NN' => 'SUM(Hour.day_off_id = 13)'
my foreach loop in controller:
foreach ($users as $user){
$set_of_days = $this->Hour->find('all', array(
'fields' => array('hour_from', 'hour_to', 'day_off_id', 'night_hours', 'half_hours', 'NN'),
'conditions' =>
array('subordinate_id' => $user['User']['id'],
'date(Hour.date) BETWEEN ? AND ?' => array($date_from, $date_to))));
its working fine but when i'll have 4k users in one view it will kill db, i wanted to join with table users with hours but i get error that column night_hours don't exist, do you guys know any way around?
Here is one of queries :
SELECT `Hour`.`hour_from`, `Hour`.`hour_to`, `Hour`.`day_off_id`, (SUM(`Hour`.`night`)) AS `Hour__night_hours`, (SUM(`Hour`.`half`)) AS `Hour__half_hours`, (SUM(`Hour`.`day_off_id` = 13)) AS `Hour__NN` FROM `kadry`.`hours` AS `Hour` WHERE `subordinate_id` = 193 AND date(`Hour`.`date`) BETWEEN '2014-01-11' AND '2014-02-11'
You dont have thiese columns 'night_hours', 'half_hours' , in your query you gave it different alias
try this
'fields' => array('hour_from', 'hour_to', 'day_off_id', 'Hour__night_hours', 'Hour__half_hours', 'NN'),
you ave aliases like that in your query
SELECT `Hour`.`hour_from`,
`Hour`.`hour_to`,
`Hour`.`day_off_id`,
(SUM(`Hour`.`night`)) AS `Hour__night_hours`,
^^^^^^^^^^^^^^^^^^^//---> here your alias
(SUM(`Hour`.`half`)) AS `Hour__half_hours`,
^^^^^^^^^^^^^^^^^^ //---> here your alias
......
......

get a single value from a table using the query() method inside a model

I have a very complex setup on my tables and achieving this via any of the find() methods is not an option for me, since I would need to fix relationships between my tables and I don't have the time right now, so I'm looking for a simple fix here.
All I want to achieve is run a query like this:
SELECT MAX( id ) as max FROM MyTable WHERE another_field_id = $another_field_id
Then, I need to assign that single id to a variable for later use.
The way I have it now it returns something like [{{max: 16}}], I'm aware I may be able to do some PHP on this result set to get the single value I need, but I was hoping there was already a way to do this on CakePHP.
Assuming you have a model for your table and your are using CakePHP 2.x, do:
$result = $this->MyTable->field('id', array('1=1'), 'id DESC');
This will return a single value.
see Model::field()
This example is directly from the CakePHP documentation. it seems you can use the find method of a model to get count
$total = $this->Article->find('count');
$pending = $this->Article->find('count', array(
'conditions' => array('Article.status' => 'pending')
));
$authors = $this->Article->User->find('count');
$publishedAuthors = $this->Article->find('count', array(
'fields' => 'DISTINCT Article.user_id',
'conditions' => array('Article.status !=' => 'pending')
));

Search similar results

In my database, I will have college building rooms (such as B100, A200, TLAB100) and I want it so that when people search for a specific room (such as B101, B102) it will return the building name without the ending number, so: B100.
My controller so far looks like this:
$results = $this->Building->find('all', array(
'conditions' => array(
'Building.building LIKE' => $this->data['Food']['q']
)
)
);
But I believe LIKE isn't the right command for it. Because it's not working that way
Why Like is not right?
$likeSmth = substr($this->data['Food']['q'], 0, -1);
'SELECT * FROM tbl WHERE roomnumber LIKE '.$likeSmth.'%'
and etc.

How to insert value of subquery using Active Record?

i use Active record for inserting values to DB.
All other type of queries i do with custom query as it's much easier but the active record insert is quite nice.
So i have this code :
$comment = array (
'point_id' => $object->id,
'title' => $object->title,
'comment' => $object->comment,
'author_name' => $object->author_name,
'is_temp' => 0,
'parent_id' => $object->parent_id
);
return $this->db->insert('comments', $comment);
Now i want to be able to set is_temp as a subquery result, which is :
(SELECT allow_user_comments from subjects where id='somevalue')
How would one achive that?
I was hoping to avoid using third party libraries.
Well, i doubt the fact that that's how you're supposed to do it, but ain't CI all about that?
This is how i got it to work (removing is_temp from the $comment array ofcourse):
$this->db->set($comment);
$this->db->set('is_temp',
'(SELECT allow_user_comments from subjects where id='.$subject_id.')',FALSE);
$this->db->insert('comments');
Feel free to use https://github.com/NTICompass/CodeIgniter-Subqueries. I have used it and it works! Hope it would be useful. :-)

Categories