How build this query with YIi query builder
SELECT *
FROM `table`
WHERE type_item = 2 AND name_item LIke '%name%'
I tried so
return Yii::app()->db->createCommand()
->select('*')
->from('{{event_field_variants}}')
->where('type_item = :type AND name_item LIKE "%:substr%"', array(':type' => '2', ':substr' => 'name'))
->order('variant ASC')
->queryAll();
But this query get CdbcException.
On Yii documentation are examples only with like or only with simple param.
->where('name_item LIKE :substr', array(':substr' => '%name%'))
Just put it in the variables part?
Related
my sql query is
$q = "SELECT
file,
roleId,
page,
type,
userType,
COUNT(DISTINCT($a)) as 'a',
COUNT(DISTINCT($b)) as 'b'
FROM table_name
WHERE
course IN ($type)
AND date BETWEEN '$startDate' AND '$endDate'
AND (course_1 is NULL OR course_1 NOT IN ('ABCD'))
AND deleted IS NULL
AND type LIKE '%Professor%'
AND action = 'submit'
GROUP BY file, roleId";
I want to convert that query into laravel query builder like
$orders = DB::table('table_name')
->select('file', 'roleId', 'page', 'type', userType DB::raw('COUNT(DISTINCT(($a)) as 'a'))
->groupBy('file', 'roleId')
->get();
Do understand how to add the other COUNT into it and how and where to chain the ->where() ?
<?php
$orders = DB::table('table_name')
->whereIn('course', $courseTypes)
->whereBetween('date', [$startDate, $endDate])
->where(function($q){
return $q->whereNull('course_1')
->orWhereNotIn('course_1', $courseArrayToFilter);
})
->whereNull('deleted')
->where('type', 'like', '%Professor%')
->where('action', 'submit')
->groupBy('file', 'roleId')
->select(
'file',
'roleId',
'page',
'type',
'userType',
\DB::raw("COUNT(DISTINCT($a)) as a"),
\DB::raw("COUNT(DISTINCT($b) as b")
)
->get();
Maybe in a cleanest way doing this:
Use the Model instance in inspite of invoke the DB facade
Use whereRaw to pass complex or pure SQL queries
Use selectRaw() to process pure SQL queries for instance functions like COUNT
Use Multiple WHERE to emulate AND operator
Use whereIn to filter ranges of data
You need to GROUP BY all columns in your SELECT you have an error at this point, I mean your query is wrong
Code
$data = Model::select('file', 'roleId', 'page', 'type', 'userType')
->selectRaw('COUNT(DISTINCT($a)) as a')
->selectRaw('COUNT(DISTINCT($b)) as b')
->whereRaw('type IN $type')
->whereIn('date', [$startDate, $endDate])
->whereRaw("course_1 IS NULL OR course_1 NOT IN('ABCD')")
->whereNull('deleted')
->where('type', 'LIKE', "%".'Professor'."%")
->where('action', '=', 'submit')
->groupBy('file', 'roleId', 'page', 'type', 'userType')
->get();
I have a working SQL query.
SELECT stuid,grade,SUM(full_amount) FROM due_payments group by stuid having SUM(full_amount) !=15600
This is working fine in MySQL workbench and phpmyadmin,But i cant seems to get this work in Laravel 5.3
I tried this on Laravel app with no Luck
$someVariable = Input::get(15600);
$results = DB::select( DB::raw("SELECT stuid,grade,SUM(full_amount) FROM due_payments
group by stuid having SUM(full_amount) =:somevariable)", array(
'somevariable' => $someVariable,
)));
Can someone Help me with this.Thank You.
First if all Input::get() doesn't take value as argument but the element name
$someVariable = Input::get(15600);
You can just use $someVariable = 15600;
Then use Query Builder rather than Raw SQL query
$results = DB::table('due_payments')
->select(array('stuid', 'grade', DB::raw('SUM(full_amount)')))
->groupBy('stuid')
->havingRaw('SUM(full_amount) != '.$someVariable)
->get();
Use query builder.
$results = DB::table('due_payments')
->select('stuid', 'grade',DB::raw('SUM(full_amount)'))
->groupBy('stuid')
->havingRaw('SUM(full_amount) != 15600')
->get();
I want to get those records whose date_last_copied field is empty or less than the current date. I tried this, but it did not give me the desired result:
$tasks = $this->Control->query("
SELECT *
FROM
`controls`
WHERE
`owner_id` = ".$user_id."
AND `control_frequency_id` = ".CONTROL_FREQUENCY_DAILY."
OR `date_last_copied` = ''
OR `date_last_copied` < ". strtotime(Date('Y-m-d'))."
");
Current query looks something like this, I think. That is, find the records with the correct owner_id and frequency_id, where the date_last_copied is null or less than a certain date. Is that logic correct?
SELECT *
FROM controls
WHERE owner_id = ::owner_id::
AND control_frequency_id = ::frequency_id::
AND (
date_last_copied IS NULL
OR date_last_copied < ::date::
)
But we should really be using the CakePHP query builder, rather than running raw SQL. This article gives some details. If I were to take a stab at a solution, we'd want something like the following. But we ideally want someone from the CakePHP community to chime in here. EDIT: Note that this seems to be for CakePHP 3.0, only.
// Build the query
$query = TableRegistry::get('controls')
->find()
->where([
'owner_id' => $ownerId,
'control_frequency_id' => $frequencyId,
'OR' => [
['date_last_copied IS' => null],
['date_last_copied <' => $date]
]
]);
// To make sure the query is what we wanted
debug($query);
// To get all the results of the query
foreach ($query as $control) {
. . .
}
I'm suggesting this, rather than the raw SQL string you have above, because:
We can now leverage the ORM model of CakePHP.
We don't have to worry about SQL injection, which you're currently vulnerable to.
EDIT: OK, this is a guess at the syntax applicable for CakePHP 2.0... YMMV
$controls = $this->controls->find('all', [
'conditions' => [
'owner_id' => $ownerId,
'control_frequency_id' => $frequencyId,
'OR' => [
['date_last_copied IS' => null],
['date_last_copied <' => $date]
]
]
];
Otherwise, we just use the raw query as a prepared statement:
$result = $this->getDataSource()->fetchAll("
SELECT *
FROM controls
WHERE owner_id = ?
AND control_frequency_id = ?
AND (
date_last_copied IS NULL
OR date_last_copied < ?
)",
[$ownerId, $frequencyId, $date]
);
Not sure about your whole logic but your final query statement should be something like:
SELECT * FROM `controls` WHERE (`owner_id` = <some owner_id>)
AND (`control_frequency_id` = <some id value>)
AND (`date_last_copied` = '' OR
`date_last_copied` IS NULL OR
`date_last_copied` < CURDATE() )
Use parentheses carefully to match your logic.
Always specify the version of cakePHP you are using for your App.
This query should work fine in CakePHP 3.0 for SQL AND and OR.
$query = ModelName>find()
->where(['colunm' => 'condition'])
->orWhere(['colunm' => 'otherCondition'])
->andWhere([
'colunm' => 'anotherContion',
'view_count >' => 10
])
->orWhere(['colunm' => 'moreConditions']);
I have tried to make codeigniter query from mysql query
my mysql query is:
select *
from class_routine
where
semester='$semester'
and day='$day'
and time_schedule='$time_schedule'
and (batch='$batch' or section='$section' or teacher='$teacher' or room='$room');
for above query what will be the codeigniter query ?
I will use this query in model.
First, you should consider looking at the Documentation before asking any question, then specify what you've looked at and what you did try, posting your code.
Anyways, try this and let me know:
$this->db->where(array('semester' => $semester, 'day' => $day, 'time_schedule' => $time_scehdule));
$this->db->where("batch = $batch OR section = $section OR teacher = $teacher OR room = $room", NULL, FALSE);
$result = $this->db->get('class_routine')->result();
When in doubt is perfectly safe to use a normal query:
$result = $this->db->query("SELECT * FROM ....")->result();
I have a problem regarding merge of multiple queries.
In Yii 1.x you could merge a CDbCriteria with
$criteria->merge($otherCriteria)
How can I achieve the same nested conditions etc with queries in Yii2?
Edit:
Let's say I want separate queries to form subqueries. And after all subqueries are done I want to merge them together to the one big query.
There is no CDbCriteria concept in Yii2 anymore. Instead you can refer to the following classes:
http://www.yiiframework.com/doc-2.0/yii-db-query.html (yii\db\Query)
http://www.yiiframework.com/doc-2.0/yii-db-activequery.html (yii\db\ActiveQuery)
All you did before with CDbCriteria now you can do with above classes. So, there will be no need to merge two criteria with each other.
update
Yii2 also supports sub-queries like below (as Yii2's official guide):
$subQuery = (new Query)->select('COUNT(*)')->from('user');
$query = (new Query)->select(['id', 'count' => $subQuery])->from('post');
Which results in:
SELECT `id`, (SELECT COUNT(*) FROM `user`) AS `count` FROM `post`
http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html#building-query
I also recently ran into this issue. Complete fusion of queries (select, join etc.) does not exist (as I understand it). But you can manually merge conditions, for example:
$query1 = \app\models\User::find()
->where(['column1' => 'value1', 'column2' => 'value2']);
$query2 = \app\models\User::find()
->where(['and', '[[column3]] = :column3', '[[column4]] = :column4'])
->addParams([
':column3' => 'value3',
':column4' => 'value4'
]);
// merge conditions
$query1->orWhere($query2->where);
$query1->addParams($query2->params);
// build SQL
echo $query1->createCommand()->rawSql;
Built SQL:
SELECT * FROM `yii2_user` WHERE
((`column1`='value1') AND (`column2`='value2')) OR
((`column3` = 'value3') AND (`column4` = 'value4'))
In addition to both the excellent answers above, should you need to merge two conditions to send on to a method which takes a 'condition' parameter in the same format as where(), then you can either build your own array:
$condition1 = ['column1' => 'value1', 'column2' => 'value2'];
$condition2 = ['column3' => 'value3', 'column4' => 'value4'];
$condition = [
'or',
$condition1,
$condition2,
];
$model->updateAll([ 'column5' => 'value5' ], $condition);
Or, if it feels more logical, you can use a temporary query object to build the conditions up and merge, etc. Then pass the generated where condition from it, e.g.:
$query1 = new \yii\db\Query;
$query1->andWhere(['column1' => 'value1', 'column2' => 'value2']);
$query2 = new \yii\db\Query;
$query2->andWhere(['column3' => 'value3', 'column4' => 'value4']);
$query = new \yii\db\Query;
$query->where($query1->where)
->orWhere($query2->where);
$model->updateAll([ 'column5' => 'value5' ], $query->where);
Obviously, this makes more sense when the queries or conditions are built up elsewhere in the code and separately passed the the place where the model method is executed.