Sql query in yii2 - php

I would like to execute such a command:
SELECT number.phone_number
FROM number
LEFT JOIN ordered_number
ON ordered_number.number_id=number.id
WHERE ordered_number.order_id=123
with Yii2. I do this:
$numery = Number::find()
->select('number.phone_number')
->leftJoin('ordered_number', ['ordered_number.number_id' => 'number.id'])
->where(['ordered_number.order_id' => 123])
->createCommand()
->rawSql;
But I get then this:
'SELECT `number`.`phone_number` FROM `number` LEFT JOIN `ordered_number` ON `ordered_number`.`number_id`='number.id' WHERE `ordered_number`.`order_id`=123'
Which doesn't work. When I put the first thing right into my base, I get 4 results, which is correct. But when I do (I think exactly the same) with Yii, I have troubles, because it is null. The only differences between what I have written and what appears after rawSql, are ` and '.

Sorry, I've just read docs for this method - it should be:
->leftJoin('ordered_number', 'ordered_number.number_id = number.id')
because using the where() kind of conditions with array leads to comparing field to string.

Maybe this link could help you a lot , the comments of ActiveRecord.

Related

Codeigniter, join of two tables with a WHERE clause

I've this code:
public function getAllAccess(){
$this->db->select('accesscode');
$this->db->where(array('chain_code' => '123');
$this->db->order_by('dateandtime', 'desc');
$this->db->limit($this->config->item('access_limit'));
return $this->db->get('accesstable')->result();
}
I need to join it with another table (codenamed table), I've to tell it this. Not really a literal query but what I want to achieve:
SELECT * accesscode, dateandtime FROM access table WHERE chain_code = '123' AND codenames.accselect_lista != 0
So basically accesstable has a column code which is a number, let us say 33, this number is also present in the codenames table; in this last table there is a field accselect_lista.
So I have to select only the accselect_lista != 0 and from there get the corrisponding accesstable rows where codenames are the ones selected in the codenames.
Looking for this?
SELECT *
FROM access_table a INNER JOIN codenames c ON
a.chain_code = c.chain_code
WHERE a.chain_code = '123' AND
c.accselect_lista != 0
It will bring up all columns from both tables for the specified criteria. The table and column names need to be exact, obviously.
Good start! But I think you might be getting a few techniques mixed up here.
Firstly, there are two main ways to run multiple where queries. You can use an associative array (like you've started to do there).
$this->db->where(array('accesstable.chain_code' => '123', 'codenames.accselect_lista !=' => 0));
Note that I've appended the table name to each column. Also notice that you can add alternative operators if you include them in the same block as the column name.
Alternatively you can give each their own line. I prefer this method because I think its a bit easier to read. Both will accomplish the same thing.
$this->db->where('accesstable.chain_code', '123');
$this->db->where('codenames.accselect_lista !=', 0);
Active record will format the query with 'and' etc on its own.
The easiest way to add the join is to use from with join.
$this->db->from('accesstable');
$this->db->join('codenames', 'codenames.accselect_lista = accesstable.code');
When using from, you don't need to include the table name in get, so to run the query you can now just use something like:
$query = $this->db->get();
return $query->result();
Check out Codeigniter's Active Record documentation if you haven't already, it goes into a lot more detail with lots of examples.

Zend Framewrok 2: How to write custom query using tablegateway

I need to write a update query in a model which use tablegateway. The update query sql like following.
UPDATE `config_settings` SET `CS_value` = CASE `CS_option`
WHEN 'CATEGORY_BANNER_MIN_WIDTH' THEN '$data->CATEGORY_BANNER_MIN_WIDTH'
WHEN 'CATEGORY_BANNER_MAX_WIDTH' THEN '$data->CATEGORY_BANNER_MAX_WIDTH'
WHEN 'CATEGORY_PROMOTION_MIN_WIDTH' THEN '$data->CATEGORY_PROMOTION_MIN_WIDTH'
WHEN 'CATEGORY_PROMOTION_MAX_WIDTH' THEN '$data->CATEGORY_PROMOTION_MAX_WIDTH'
WHEN 'PRODUCT_LARGE_IMAGE_WIDTH' THEN '$data->PRODUCT_LARGE_IMAGE_WIDTH'
WHEN 'PRODUCT_MEDIUM_IMAGE_WIDTH' THEN '$data->PRODUCT_MEDIUM_IMAGE_WIDTH'
WHEN 'PRODUCT_SMALL_IMAGE_WIDTH' THEN '$data->PRODUCT_SMALL_IMAGE_WIDTH'
ELSE `CS_value`
END;
I have no idea how to implement this. The update method of tablegateway only take array of table field name and its value. So how to write this query.
I know that i can execute this query using db adapter raw sql query but i don't want this. Beside this, some times we need to some custom query in select method of tablegateway. But i found no stable way in tablegateway.
For example:
select sum(CASE WHEN answers.type = 'his' THEN 1 ELSE 3 END) AS totalScore
FROM users_questions_answers join answers on cast(answers.id as int(8))=
users_questions_answers.answer_id group by users_questions_answers.user_id
How can i proceed in this situation. Any zend 2 expert suggestion will highly appreciated.
Thanks for your kind consideration.
Try this -
$this->tablegateway->update(array('CS_value' => new \Zend\Db\Sql\Expression('CASE CS_option
WHEN "CATEGORY_BANNER_MIN_WIDTH" THEN ?
WHEN "CATEGORY_BANNER_MAX_WIDTH" THEN ?
WHEN "CATEGORY_PROMOTION_MIN_WIDTH" THEN ?
WHEN "CATEGORY_PROMOTION_MAX_WIDTH" THEN ?
WHEN "PRODUCT_LARGE_IMAGE_WIDTH" THEN ?
WHEN "PRODUCT_MEDIUM_IMAGE_WIDTH" THEN ?
WHEN "PRODUCT_SMALL_IMAGE_WIDTH" THEN ?
ELSE CS_value END',
array($data->CATEGORY_BANNER_MIN_WIDTH, $data->CATEGORY_BANNER_MAX_WIDTH, $data->CATEGORY_PROMOTION_MIN_WIDTH, $data->CATEGORY_PROMOTION_MAX_WIDTH, $data->PRODUCT_LARGE_IMAGE_WIDTH, $data->PRODUCT_MEDIUM_IMAGE_WIDTH, $data->PRODUCT_SMALL_IMAGE_WIDTH))));
If CATEGORY_BANNER_MIN_WIDTH like used in the query are some constants then just remove the double quotes around it.
I have tried a similar query to the above one and it works just fine.

Laravel Fluent Query Builder Update Query

I want to add two columns while using update, like this:
Update purchase_stock inner join stock on purchase_stock.fkstockid=stock.stockid SET currentavailable=currentavailable+subquantity where fkorderid='1';
Here is the current Fluent code:
DB::table('purchase_stock')->join('stock','stock.stockid','=','purchase_stock.fkstockid')->where('fkorderid',$orderId)->update(array('currentavailable'=>'currentavailable'+'subquantity'));**
But it throws error as below:
"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"syntax error, unexpected '=>'"
Does any one have solution?
You were very close with your fluent attempt, but there were two issues:
The plus sign needs to be inside the quotes, since you want the math done in SQL, not in PHP.
Need a DB::raw() around the value so Laravel doesn't think you're actually trying to set it to the string "currentavailable + subquantity"
So the final product looks like this:
DB::table('purchase_stock')
->join('stock', 'stock.stockid', '=', 'purchase_stock.fkstockid')
->where('fkorderid', $orderId)
->update(['currentavailable' => DB::raw('currentavailable + subquantity')]);
Мaybe you need to set these two fields from which tables. Exampl. DB::table('purchase_stock')->join('stock','stock.stockid','=','purchase_stock.fkstockid')->where('fkorderid',$orderId)->update(array('stock.currentavailable'=>'stock.currentavailable'+'stock.subquantity'));
Ohk!
I already tried this one but it is not working
As of now I am using DB::statement('') and it's working
So I have written whole update query within statement and it's working as somewhere I have read that it will not be helpful to return result set but will work with insert or update.

If in Sum combined in SQL query, and Yii ActiveRecord

First of all, sorry for my English. I need some help with this. Recently I started my first project with Yii, and everything is great, framework seems to be perfect, but I have a little problem with selecting records from the database using ActiveRecord.
Let's say that I have following code:
$criteria = new CDbCriteria();
$criteria->select = '*, user.*, sum(if(points > 0, 1, 0)) as rank_points, sum(points) as all_points, count(*) as count_all';
$criteria->group = 'user_id';
$criteria->order = 'all_points desc';
$users = Types::model()
->with('user')
->findAll($criteria);
I have problems with this
sum(if(points > 0, 1, 0)) as rank_points
when I'm using it, I get the following error:
Active record "Types" is trying to select an invalid column "sum(if(points > 0". Note, the column must exist in the table or be an expression with alias.
The problem is that this query is correct, and I can use it manually, or (I haven't tried but I think it should work) with query builder. I'm determined to do this with AR, so here is my question; is it possible, to do this as stated? Am I doing something wrong, or is it a more complicated problem?
Thanks in advance for every reply.
Just specify the select as a array
$criteria->select=array('*', 'sum(if(points > 0, 1, 0)) as rank_points','sum(points) as all_points', 'count(*) as count_all');
The problem with your code is that as your select parameter is a string, Yii try to get all columns by exploding with a , and the , in your IF statement makes yii to think it as two seperate select values

Codeigniter ActiveRecord: join backticking

I've a simple question: how can I use CodeIgniter's ActiveRecord join function? I want this:
LEFT JOIN cimke ON (mk_terem.id_kicsoda=5 AND mk_terem.id_target=cimke.id_cimke)
LEFT JOIN tanar ON (mk_terem.id_kicsoda=1 AND mk_terem.id_target=tanar.id_tanar)
But if I use $this->db->join(cimke,"mk_terem.id_kicsoda=5 AND mk_terem.id_target=cimke.id_cimke"), the value 5 will be between backticks.
How can I do this?
UPDATE
What I want? If mk_terem.id_kicsoda is 1, then I want tanar.nev and when mk_terem.id_kicsoda is 5, I want cimke.nev.
The full SQL-query:
SELECT
terem.nev terem_nev,
elem_tipus.nev tipus_nev,
(IFNULL(cimke.nev,tanar.nev)) nev
FROM mk_terem
LEFT JOIN terem ON mk_terem.id_terem=terem.id_terem
LEFT JOIN cimke ON (mk_terem.id_kicsoda=5 AND mk_terem.id_target=cimke.id_cimke)
LEFT JOIN tanar ON (mk_terem.id_kicsoda=1 AND mk_terem.id_target=tanar.id_tanar)
LEFT JOIN elem_tipus ON (mk_terem.id_kicsoda=elem_tipus.id_kicsoda)
Only a simple workaround, ugly, not elegant, but it works in this case:
$original_reserved = $this->db->_reserved_identifiers;
$this->db->_reserved_identifiers[] = 5;
$this->db->_reserved_identifiers[] = 1;
// or any other values
$this->db->join('with critical values and conditions');
// some db-stuff
$this->db->_reserved_identifiers = $original_reserved;
If anybody knows better please show it!
$this->db->join('cimke', 'mk_terem.id_target = cimke.id_cimke');
$this->db->join('tanar', 'mk_terem.id_target = tanar.id_tanar');
$this->db->where('mk_terem.id_kicsoda', 5);
$this->db->where('mk_terem.id_kicsoda', 1);
or use
$this->db->query('AND_YOUR_RAW_SQL_QUERY_HERE');
Another simple solution would be to temporarily set the protect_identifiers off like so:
$this->db->_protect_identifiers = false;
After making the query you could set it back to true
I know i am very answering this question very late. Just i am sharing my knowledge. It may help us to known something. If I am wrong, Please tell me. I am answering this question by the full query you posted on your question. Kindly check it below.
$this->db->from('mk_terem');
$this->db->select('terem.nev terem_nev, elem_tipus.nev tipus_nev, (IFNULL(cimke.nev,tanar.nev)) nev');
$this->db->join('terem','mk_terem.id_terem=terem.id_terem','left');
$this->db->join('cimke','(mk_terem.id_kicsoda=5 AND mk_terem.id_target=cimke.id_cimke)','left');
$this->db->join('tanar','(mk_terem.id_kicsoda=1 AND mk_terem.id_target=tanar.id_tanar)','left');
$this->db->join('elem_tipus','(mk_terem.id_kicsoda=elem_tipus.id_kicsoda)','left'); $this->db->get();
I got the query which you posted in the question as full Query. Check it below.
SELECT `terem`.`nev` terem_nev, `elem_tipus`.`nev` tipus_nev, (IFNULL(cimke.nev, `tanar`.`nev))` nev FROM (`mk_terem`) LEFT JOIN `terem` ON `mk_terem`.`id_terem`=`terem`.`id_terem` LEFT JOIN `cimke` ON `mk_terem`.`id_kicsoda`=`5` AND mk_terem.id_target=cimke.id_cimke) LEFT JOIN `tanar` ON `mk_terem`.`id_kicsoda`=`1` AND mk_terem.id_target=tanar.id_tanar) LEFT JOIN `elem_tipus` ON `mk_terem`.`id_kicsoda`=`elem_tipus`.`id_kicsoda)`
I believe everything is possible to do by codeignitor Active record. No need to execute the query in $this->db->query() as raw sql.
#uzsolt: I am explaining this because of the argument you made under the topic "http://stackoverflow.com/questions/8344769/writing-sql-queries-in-codeigniter-2-0". And I will try your other bugs you posted under the above URL too shortly and get back to you. If i am anything wrong, kindly let me know. Thanks. :)
If you swap the conditions around AND, it will work! CodeIgniter only escapes the first part of the condition.
So, inthis should work:
$this->db->join('cimke',"mk_terem.id_kicsoda = 5 AND mk_terem.id_target = cimke.id_cimke", "left")

Categories