I am using Query Builder with multiple where clause. When I use this query,
$query1 = new \yii\db\Query();
$query1->select('*')
->from('assessment_score ca')
->where(['AND','ca.is_status' => 0, 'ca.assessment_type' => 'CONTINUOUS ASSESSMENT', 'ca.ca_type' => 'CONTINUOUS ASSESSMENT'])
->andFilterWhere(['ca.state_office_id' => $model->report_state_office_id])
->andFilterWhere(['ca.study_centre_id' => $model->report_study_centre_id])
->andFilterWhere(['ca.programme_id' => $model->report_programme_id])
->andFilterWhere(['ca.department_id' => $model->report_department_id])
->andFilterWhere(['ca.academic_level_id' => $model->report_academic_level_id])
->andFilterWhere(['ca.academic_year_id' => $model->report_academic_year_id])
->andFilterWhere(['ca.academic_semester_id' => $model->report_academic_semester_id])
->andFilterWhere(['ca.course_id' => $model->report_course_id]);
$command=$query1->createCommand();
$ca_data=$command->queryAll();
I got this error
Then, when I changed the code to this, no response:
$selected_list = $_POST['ca'];
$query1 = new \yii\db\Query();
$query1->select('*')
->from('assessment_score ca')
->where(['ca.is_status' => 0])
->andWhere(['ca.assessment_type' => 'CONTINUOUS ASSESSMENT'])
->andWhere(['ca.ca_type' => 'CONTINUOUS ASSESSMENT'])
->andFilterWhere(['ca.state_office_id' => $model->report_state_office_id])
->andFilterWhere(['ca.study_centre_id' => $model->report_study_centre_id])
->andFilterWhere(['ca.programme_id' => $model->report_programme_id])
->andFilterWhere(['ca.department_id' => $model->report_department_id])
->andFilterWhere(['ca.academic_level_id' => $model->report_academic_level_id])
->andFilterWhere(['ca.academic_year_id' => $model->report_academic_year_id])
->andFilterWhere(['ca.academic_semester_id' => $model->report_academic_semester_id])
->andFilterWhere(['ca.course_id' => $model->report_course_id]);
$command=$query1->createCommand();
$ca_data=$command->queryAll();
How do I re-write the code appropriately to solve the issue of multiple where clause?
You might need to change the query format for the where() statement as you need to provide every condition (name=>value pair) as a separate array rather than just name=>value pairs, you currently have
->where(['AND', 'ca.is_status' => 0, 'ca.assessment_type' => 'CONTINUOUS ASSESSMENT', 'ca.ca_type' => 'CONTINUOUS ASSESSMENT'])
which will create the query like below if no other parameter is provided for andFilterWhere() statements.
SELECT * FROM `assessment_score` `ca`
WHERE (0)
AND (CONTINUOUS ASSESSMENT) AND (CONTINUOUS ASSESSMENT)
which is incorrect and throwing the error, you can notice that in your Exception image, so change it to the one below
->where(['AND',
['ca.is_status' => 0],
['ca.assessment_type' => 'CONTINUOUS ASSESSMENT'],
['ca.ca_type' => 'CONTINUOUS ASSESSMENT']
])
which will output the query like
SELECT * FROM `assessment_score` `ca`
WHERE (`ca`.`is_status`=0)
AND (`ca`.`assessment_type`='CONTINUOUS ASSESSMENT')
AND (`ca`.`ca_type`='CONTINUOUS ASSESSMENT')
Your complete query should look like this
$query1 = new \yii\db\Query();
$query1->select('*')
->from('assessment_score ca')
->where(['AND',
['ca.is_status' => 0],
['ca.assessment_type' => 'CONTINUOUS ASSESSMENT'],
['ca.ca_type' => 'CONTINUOUS ASSESSMENT']
])
->andFilterWhere(['ca.state_office_id' => $model->report_state_office_id])
->andFilterWhere(['ca.study_centre_id' => $model->report_study_centre_id])
->andFilterWhere(['ca.programme_id' => $model->report_programme_id])
->andFilterWhere(['ca.department_id' => $model->report_department_id])
->andFilterWhere(['ca.academic_level_id' => $model->report_academic_level_id])
->andFilterWhere(['ca.academic_year_id' => $model->report_academic_year_id])
->andFilterWhere(['ca.academic_semester_id' => $model->report_academic_semester_id])
->andFilterWhere(['ca.course_id' => $model->report_course_id]);
$command = $query1->createCommand();
$ca_data = $command->queryAll();
based on yii2 guide for Operator Format
Operator format allows you to specify arbitrary conditions in a
programmatic way. It takes the following format:
[operator, operand1, operand2, ...] where the operands can each be
specified in string format, hash format or operator format
recursively, while the operator can be one of the following:
and: the operands should be concatenated together using AND. For
example, ['and', 'id=1', 'id=2']
so in your case should be
->where(['AND', 'ca.is_status = 0',
"ca.assessment_type = 'CONTINUOUS ASSESSMENT'",
"ca.ca_type = 'CONTINUOUS ASSESSMENT'"])
https://www.yiiframework.com/doc/guide/2.0/en/db-query-builder#operator-format
All you need is to remove AND from array passed to where():
->where([
'ca.is_status' => 0,
'ca.assessment_type' => 'CONTINUOUS ASSESSMENT',
'ca.ca_type' => 'CONTINUOUS ASSESSMENT'
])
If you pass associative array, it will be treated as pairs of column-value for conditions for WHERE in query. If you pass AND as first element, it is no longer a associative array, and query builder will ignore keys and only combine values as complete condition.
Related
I am querying a database table conveniently named order and because of that I had to set 'quoteIdentifiers' => true in my app.php configuration. However, when I'm putting function names into the fields configuration of my find() call, CakePHP quotes them too.
$orders->find('all', array(
'fields' => array(
'DATE(Orders.date_added)',
'COUNT(*)',
),
'conditions' => array(
'Orders.order_status_id <>' => 0,
),
'group' => array(
'DATE(Orders.date_added)',
),
));
The query above ends up calling
SELECT <...>, `DATE(Orders.date_added)` FROM `order` <...>
which obviously throws an error.
I googled a lot, tried this:
$orders = $orders->find('all', array(
'conditions' => array(
'Orders.order_status_id <>' => 0,
),
'group' => array(
'DATE(Orders.date_added)',
),
))->select(function($exp) {
return $exp->count('*');
});
and that didn't work either, throwing me some array_combine error.
Is there any way for me to un-quote those function names, while keeping the rest of the query quoted automatically? Here's what I'm trying to accomplish:
SELECT <...>, DATE(Orders.date_added) FROM `order` <...>
Please help.
You should use function expressions, they will not be quoted, except for arguments that are explicitly being defined as identifiers:
$query = $orders->find();
$query
->select([
'date' => $query->func()->DATE([
'Orders.date_added' => 'identifier'
]),
'count' => $query->func()->count('*')
])
->where([
'Orders.order_status_id <>' => 0
])
->group([
$query->func()->DATE([
'Orders.date_added' => 'identifier'
])
]);
I'd generally suggest that you use expressions instead of passing raw SQL snippets wherever possible, it makes generating SQL more flexible, and more cross-schema compatible.
See also
Cookbook > Database Access & ORM > Query Builder > Using SQL Functions
Using Moose, is it possible to create a builder that builds multiple attributes at once?
I have a project in which the object has several 'sets' of fields - if any member of the set is requested, I want to go ahead and populate them all. My assumption is that if I need the name, I'll also need the birthdate, and since they're in the same table, it's faster to get both in one query.
I'm not sure if my question is clear enough, but hopefully some sample code will make it clear.
What I have:
Package WidgetPerson;
use Moose;
has id => (is => 'ro', isa => 'Int' );
has name => (is => 'ro', lazy => 1, builder => '_build_name');
has birthdate => (is => 'ro', lazy => 1, builder => '_build_birthdate');
has address => (is => 'ro', lazy => 1, builder => '_build_address');
sub _build_name {
my $self = shift;
my ($name) = $dbh->selectrow_array("SELECT name FROM people WHERE id = ?", {}, $self->id);
return $name;
}
sub _build_birthdate {
my $self = shift;
my ($date) = $dbh->selectrow_array("SELECT birthdate FROM people WHERE id = ?", {}, $self->id);
return $date;
}
sub _build_address {
my $self = shift;
my ($date) = $dbh->selectrow_array("SELECT address FROM addresses WHERE person_id = ?", {}, $self->id);
return $date;
}
But what I want is:
has name => (is => 'ro', isa => 'Str', lazy => 1, builder => '_build_stuff');
has birthdate => (is => 'ro', isa => 'Date', lazy => 1, builder => '_build_stuff');
has address => (is => 'ro', isa => 'Address', lazy => 1, builder => '_build_address');
sub _build_stuff {
my $self = shift;
my ($name, $date) = $dbh->selectrow_array("SELECT name, birthdate FROM people WHERE id = ?", {}, $self->id);
$self->name($name);
$self->birthdate($date);
}
sub _build_address {
#same as before
}
What I do in this case, when I don't want to have a separate object as in Ether's answer, is have a lazily built attribute for the intermediate state. So, for example:
has raw_row => (is => 'ro', init_arg => undef, lazy => 1, builder => '_build_raw_row');
has birthdate => (is => 'ro', lazy => 1, builder => '_build_birthdate');
sub _build_raw_row {
$dbh->selectrow_hashref(...);
}
sub _build_birthdate {
my $self = shift;
return $self->raw_row->{birthdate};
}
Repeat the same pattern as birthdate for name, etc.
Reading any of the individual attributes will try to get data from raw_row, whose lazy builder will only run the SQL once. Since your attributes are all readonly, you don't have to worry about updating any object state if one of them changes.
This pattern is useful for things like XML documents, too -- the intermediate state you save can be e.g. a DOM, with individual attributes being lazily built from XPath expressions or what-have-you.
No, an attribute builder can only return one value at a time. You could build both by having each builder set the value of the other attribute before returning, but that gets ugly pretty quickly...
However, if you generally have two pieces of data that go together in some way (e.g. coming from the same DB query as in your case), you can store these values together in one attribute as an object:
has birth_info => (
is => 'ro', isa => 'MyApp::Data::BirthInfo',
lazy => 1,
default => sub {
MyApp::Data::BirthInfo->new(shift->some_id)
},
handles => [ qw(birthdate name) ],
);
package MyApp::Data::BirthInfo;
use Moose;
has some_id => (
is => 'ro', isa => 'Int',
trigger => sub {
# perhaps this object self-populates from the DB when you assign its id?
# or use some other mechanism to load the row in an ORMish way (perhaps BUILD)
}
);
has birthdate => (
is => 'ro', isa => 'Str',
);
has name => (
is => 'ro', isa => 'Str',
);
I recently release an app: https://my.kendozone.com in Laravel 5.3 / MySQL
I'm getting users, but one weird thing is that my user's id are not incrementing by one.
HERE last 10 rows id :
5401
5402
5403
5404
5405
5406
5407
5408
8359
9799
The 2 ways I save my users are :
$user = User::create([
'provider' => $provider,
'provider_id' => $userData->id,
'name' => $userData->name,
'firstname' => $userData->name,
'slug' => str_slug($userData->name),
'email' => $userData->email,
'avatar' => $avatar,
'role_id' => config('constants.ROLE_USER'),
'verified' => 1,
]);
or
$user = User::create(['name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password),
'role_id' => config('constants.ROLE_USER'),
'verified' => 1,
]);
How should understand this??? Is it normal???
Does anybody have an explanation???
My id are weird because of my Functional tests.
when running, they use :
use DatabaseTransactions
that mean that all queries runs into a Transaction, but I guess it uses ids range.
I'm using Zend Framework 2.4 and trying to amend a working SQL columns select from
'content_publish_date' => 'publish_date',
to
'content_publish_date' => new \Zend\Db\Sql\Expression('DATE_FORMAT(\'content.publish_date\',\'%d/%c/%Y\')'),
produces the following SQL...
DATE_FORMAT('content.publish_date','%%d/%%c/%%Y') AS `content_publish_date`,
... which fails syntactically on MySQL (note the extra '%')
I have tried various alternatives...
'content_publish_date' => new \Zend\Db\Sql\Expression('DATE_FORMAT(content.publish_date,\'%d/%c/%Y\')'),
'content_publish_date' => new \Zend\Db\Sql\Expression('DATE_FORMAT(content.publish_date,"%d/%c/%Y")'),
... and so on, none of which has helped.
Does anyone have any idea how to use the Expression correctly to get the correct generated SQL?
The full code for this piece is as follows:
$dbSelect->join(
'content',
'content.id = category.content_id',
array(
'content_title' => 'title',
'content_html_title' => 'html_title',
'content_description' => 'description',
'content_content_text' => 'content_text',
'content_url' => 'url',
'content_url_vars' => 'url_vars',
'content_meta_keyword' => 'meta_keyword',
'content_meta_description' => 'meta_description',
'content_content_type_id' => 'content_type_id',
'content_disclaimer_id' => 'disclaimer_id',
'content_agent_target_id' => 'agent_target_id',
'content_video_position' => 'video_position',
'content_video_size' => 'video_size',
'content_creation_date' => 'creation_date',
'content_publish_date' => new \Zend\Db\Sql\Expression('DATE_FORMAT(\'content.publish_date\',\'%d/%c/%Y\')'),
'content_flag_content_url' => 'flag_content_url',
'content_flags' => 'flags'
),
\Zend\Db\Sql\Select::JOIN_LEFT
);
Thanks in advance.
I'm performing a simple query that joins two tables together. What I get is something like this.
array(
[0] => array(
'id' => 52
'name' => 'charles',
'sale_id' => 921,
'sale_time' => 1306393996,
'sale_price' => 54.21
),
[1] => array(
'id' => 52
'name' => 'charles',
'sale_id' => 922,
'sale_time' => 1306395000,
'sale_price' => 32.41
),
...
);
...which is the expected result. However, I'd like the query to return something like this:
array(
[0] => array(
'id' => 52,
'name' => 'charles',
'sales' => array(
[0] => array(
'sale_id' => 921,
'sale_time' => 1306393996,
'sale_price' => 54.21
),
[1] => array(
'sale_id' => 922,
'sale_time' => 1306395000,
'sale_price' => 32.41
),
...
)
)
)
Now I realize I could simply perform two queries, one for the user info, and another for sales, and merge those arrays together using whatever language I'm using (PHP in this case). But I have many arrays of properties and querying and merging for those seems awfully inelegant to me (although it does work). It seems to me there'd be a way to work with a single, unified object without duplicating data.
Just wondering if there was a no-brainer query, or if that's simply not easy through MySQL alone.
I would say this is not possible with MySQL alone - you have to do some tricks at application level. That is, because even if you send a single query that will bring you all the data from MySQL to your application (PHP), they will come as a denormalized array of data - your first case.
If you want to get the data as in your second case, I'd recommend using some ORM - in Ruby there is ActiveRecord, in Perl there are Class::DBi, DBIx::Class and many more - I can not name one for PHP that is able to do this, but I am sure there are plenty.