Setting a query result literal in Laravel query builder? - php

I am trying to set a column result literal with the Laravel query builder. By writing raw SQL I would achieve this with:
SELECT
`field1`,
`field2`,
'Test' AS `field3`
FROM `Test`;
Therefore MySQL will always return Test for column field3. I'm trying to do this with the query builder like select('field1', 'field2', '"Test" AS field3') but this doesn't seem to work. It will return an error that Test is not a column name.
Does anyone have an idea how I could do this?

You want the DB::raw() function:
->select('field1', 'field2', DB::raw("'Test' AS field3"))

Related

laravel select query create dynamic column name not working

I am trying Laravel join query to select the column dynamically but below line is returning error.
\DB::raw('table3.ElrA'.($effectiveYear'.-YEAR(table1.eff_date).'))
table3 having columns like this ElrA1, ElrA2 .....
common part is "ElrA" I am just making trailing number dynamically to create whole column name but it gives me err like "ElrA202-YEAR(table3.eff_date) is not a column". can you please suggest any solutions.
$query = DB::table('table1')
->join('table2', function($join) {
$join->on('table2.policy_period_id', '=', 'table1.id');
$join->where('status','1');
})
->leftjoin('table3', function($join) use($effective_date)
{
$join->on('table3.class_code', '=', 'table2.code');
$join->where('table3.date', '=', DB::raw("(select max(`date`) from table3 where date <= '".$effective_date."' limit 1)"));
})
->select(\DB::raw('table3.ElrA'.($effectiveYear'.-YEAR(table1.eff_date).')))
->where('table1.mod_id',$id);
Thanks
When you look at the error code, it says clearly that laravel try to find column ElrA202-YEAR(table3.eff_date)
What happen is because you make mistake in this part
'table3.ElrA'.($effectiveYear'.-YEAR(table1.eff_date).'
the exact part is in this one
'.-YEAR(table1.eff_date).'
because you use '' and it will parsed as string and not the variable that you want
I don't know why you will use dynamic column, but it is really not a good idea, because as the documentation says, it's very vulnerable with sql injection attack because there is no parameter binding in dynamic column. But if you know what you are doing then it's okay

PHP Yii2 MYSQL query giving wrong output

I'm executing a PHP yii2 query to get records from the database but it's not working. But I directly executed the query in the MYSQL console then it gives me the expected output.
Normal SQL
SELECT * FROM `tbl_inbox` WHERE sender_id=778 AND recipient_id=736 OR sender_id=778 AND recipient_id=736 ORDER BY timestamp DESC LIMIT 1
Above query giving me expected result but when i change to Yii2 like :
$message=Inbox::find()->select(['message'])->where(['sender_id'=>$sender_id,'recipient_id'=>$recipient_id])->orWhere(['sender_id'=>$recipient_id,'recipient_id'=>$sender_id])->andWhere(['ad_id'=>$ad_id,'category'=>$category])->orderBy(['timestamp'=>SORT_DESC])->one();
It gives me the wrong result.
What is my logic :
I have a chat on my website and I need to get the last message order by timestamp. But sender_id and the recipient will be visa versa.
How to fix ?
There are significant differences between the normal SQL version of the query and the Yii version.
1) Selected fields
The normal SQL query selects all fields, but Yii version selects only message field.
This is because the normal SQL has SELECT * FROM ... but in Yii query you are calling select(['message']). If you want to select all fields you can leave the select() method call out or you can use select('*').
2) Your conditions are different
Considering operator priority your conditions in normal SQL are:
(sender_id=778 AND recipient_id=736)
OR (sender_id=778 AND recipient_id=736)
But in your Yii version of query:
(
(sender_id=778 AND recipient_id=736)
OR (sender_id=736 AND recipient_id=778)
) AND (
ad_id=$ad_id AND category=$category
)
In your normal SQL the both sides of OR condition are same but in your Yii version the values for sender/recipient are swapped in the second argument of OR operator.
Also there is extra part added by this call andWhere(['ad_id'=>$ad_id,'category'=>$category])
$message=Inbox::find()->select(['message'])->where(['sender_id'=>$sender_id,'recipient_id'=>$recipient_id])->orWhere(['sender_id'=>$recipient_id])->orWhere(['recipient_id'=>$sender_id])->andWhere(['ad_id'=>$ad_id,'category'=>$category])->orderBy(['timestamp'=>SORT_DESC])->one();
try this
I'm getting following sql
SELECT `message` FROM `user` WHERE ((((`sender_id`='2333') AND (`recipient_id`='23222')) OR (`sender_id`='23222')) OR (`recipient_id`='23333')) AND ((`ad_id`='10') AND (`category`='1')) ORDER BY `timestamp` DESC
you can check raw sql easily, then it will be mostly straight forward how Yii Query builder works.
use following code:
$rawSql = Inbox::find()
...
->createCommand()->getRawSql();
I would change your code into this:
$message=Inbox::find()
->select(['message'])
->where([
'and',
[
'or',
['sender_id'=>$sender_id,'recipient_id'=>$recipient_id],
['sender_id'=>$recipient_id,'recipient_id'=>$sender_id]
],
['ad_id'=>$ad_id,'category'=>$category]
])
->orderBy(['timestamp'=>SORT_DESC])->one();

Laravel put NULL inside quotes

I'd like to make union query with Laravel Eloquent.
When we proceed UNION queries, there should be the same number of selected columns in both queries.
To skip that rule I would like to select NULL as Column_name,
but Laravel API automatically replaces NULL with 'Null' and that causes an error "Null column is not existed".
How to remove these automatically added quotes from Null?
That is what I have:
The first query:
...->select("Calendars.*","Services.Id as IdService","Services.Name as ServiceName","NULL as Price")
The second query:
...->select("Calendars.*","Services.Id as IdService","Services.Name as ServiceName","PaidService.Price")
Result is:
...union (select `Calendars`.*, `Services`.`Id` as `IdService`, `Services`.`Name` as `ServiceName`, `NULL` as `Price` from `Calendars`
Thanks a lot!
Consider using DB::raw for this. It will stop laravel from modifying the statement and parse it as is.
DB::raw("NULL as Price")
which will make the first query
...->select("Calendars.*",
"Services.Id as IdService",
"Services.Name as ServiceName",
DB::raw("NULL as Price"))

Yii2 - Is it possible to not quote parameters passed in by bindValues()?

I am trying to query a column with createCommand doing something like this:
Yii::$app->db->createCommand('Select column1 from table where column2 in :array)
->bindValues(['array'=>['(1,2,3,4,5)', PDO::PARAM_INT]])->queryColumn('COLUMN1');
Ideally I want my SQL statement to be executed like
select column1 from table where column2 in (1,2,3,4,5)
However when the SQL executes there is always quotes wrapped around the binded parameters like so:
select column1 from table where column2 in '(1,2,3,4,5)'
I'm not sure why this is still happening after I specify the PDO to use PDO::PARAM_INT. Isn't int supposed to not be quoted?
You could try a slightly different approach using Query Builder:
$rows = (new \yii\db\Query())
->select('column1')
->from('table')
->where(['column2' => [1,2,3,4,5]])
->column();
This has the desired effect: the where clause is automatically generated using the in (...) syntax because of the array passed in.
Not sure if you explicitly need to cast the types of the array to INT if they happen to be of type STRING internally in PHP though...

Add custom field during select mysql in laravel query

I have this query in laravel 5.2
$obj_custom_stdy_data = QstCustomStudyData::where('student_id', $this->data_user['student_id'])
->select($list_id . ' as list_id ', 'chapter_id', 'subject_id', 'subject_code_id')
->get()
->toArray();
Well I have a fixed value $list_id got from top code. Actually I want to add new field during query selection as list_id. However I got error for such that method.
When I tried in mysql IDE for example:
SELECT (1+2) as total, c.* FROM users
Then the result is no wrong at all.
Is that anyway to write in query builder for laravel instead of raw style?
You can take the use of DB::raw() method of QueryBuilder like this:
->select(DB::raw('(1+2) as total'));
See more about Query Builder's Raw Expressions
Hope this helps!

Categories