I have a table called Category with a few columns and I'm trying to get only a few out of my database.
So I've tried this:
$sql = 'SELECT uppercat AS id, COUNT(uppercat) AS uppercat FROM category GROUP BY uppercat;';
$d = Yii::app()->db->createCommand($sql)->query();
But I find the output strange. I was trying to do an array_shift but I get an error that this isn't an array. When I do a var_dump on $d:
object(CDbDataReader)[38]
private '_statement' =>
object(PDOStatement)[37]
public 'queryString' => string 'SELECT uppercat AS id, COUNT(uppercat) AS uppercat FROM category GROUP BY uppercat;' (length=100)
private '_closed' => boolean false
private '_row' => null
private '_index' => int -1
private '_e' (CComponent) => null
private '_m' (CComponent) => null
Ok.. then I did a foreach on $id:
array
'id' => string '0' (length=1)
'uppercat' => string '6' (length=1)
array
'id' => string '3' (length=1)
'uppercat' => string '2' (length=1)
array
'id' => string '6' (length=1)
'uppercat' => string '1' (length=1)
array
'id' => string '7' (length=1)
'uppercat' => string '2' (length=1)
array
'id' => string '9' (length=1)
'uppercat' => string '2' (length=1)
Then why do I get the message that $id isn't an array while it contains arrays?
Is there any other way on how to get some specific data out of my database and that I can then do an array_shift on them? I've also tried doing this with findAllBySql but then I can't reach my attribute for COUNT(uppercat) which is not in my model. I guess I'd have to add it to my model but I wouldn't like that because I need it just once.
CDbCommand's query returns a CDbDataReader object for fetching the query result. Use queryAll instead, that returns an array of rows.
However, it is nicer if you do it with CDbCriteria (you need a model property for that, you're right).
It would look something like this, assuming the property is called countUppercat.
$criteria = new CDbCriteria;
$criteria->select = 'uppercat, COUNT(uppercat) AS countUppercat';
$criteria->group = 'countUppercat';
$models = CategorieModel::model()->findAll($criteria);
Try this.. its closed which you approched used...
$sql = 'SELECT uppercat AS id, COUNT(uppercat) AS uppercat FROM categorie GROUP BY uppercat;';
$d = Yii::app()->db->createCommand($sql)->queryAll();
and after that when you want to see your array so use,
print_r($d);
so you get the array..
it will work for you..
Related
I am trying to convert "left(SchoolCode,1) = '1'" which is in the sql i was provided into a correct field for the fine where statement. I am not a sql expert here but have been looking through cakephp documentation and can't seem to find a solution. any help would be appreciated.
The app i am creating, basically has a first screen where it shows the current year and 4 check boxes each with elementary middle and high. so if elementary is selected and submit is pressed then it executes that statement below giving back all records.
select *
from MMSD.vSchoolFromCalendar
where FiscalYear = 2019
and DistrictCode = 'MA'
and summerSchool = '0'
and left(SchoolCode,1) = '1'
public function getElementary()
{
$query = $this->find()
->where([
'FiscalYear' => '2019',
'DistrictCode' => 'MA',
'summerSchool' => '0',
'left(SchoolCode,1)' => '0',
]);
return $query->toArray();
}
My result should return the data with "and left(SchoolCode,1) = '1'" as a selected where field which right now it does not.
public function getSchoolsByLevel(string $code = '0', string $isSummerSchool = '0')
{
$query = $this->find()
->where([
'FiscalYear' => $schoolYear,
'DistrictCode' => 'MA',
'summerSchool' => $isSummerSchool,
'SchoolCode like' => $code,
]);
return $query->toArray();
}
I am having an issue with Laravel and default values. I created the field in my table like so:
$table->string('title', 255)->default('');
And in the model, I have a default set again using this:
protected $attributes = [
'title' => '',
];
Yet I am always getting this error:
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column
"title" violates not-null constraint DETAIL: Failing row contains
(3dd07c7a-e3f3-4f20-8d16-0f066b219dc2, dsfs, sdfs, null, null, null,
sdfs, null, 0, 0, 0, 0, 0, 0, null, null, null). (SQL: insert into
"users" ("title", "first_name", "last_name", "email", "business_unit",
"linkedin_profile") values (, dsfs, sdfs, sdfs, , ) returning
"user_id")
My abbreviated save action (example without validation) is the following:
$data = Input::all();
$user = new Users($data);
$user->save();
The following is the $data:
array (size=12)
'_token' => string '0EI9JGmgiNDAqmv83pdQZaktyWNLiX3GB9JQSfvA' (length=40)
'first_name' => string 'ads' (length=3)
'last_name' => string 'asd' (length=3)
'email' => string 'asd' (length=3)
'title' => null
'business_unit' => null
'linkedin_profile' => null
'is_admin' => string '0' (length=1)
'is_employee' => string '0' (length=1)
'is_manager' => string '0' (length=1)
'is_trainer' => string '0' (length=1)
'rt' => string '/users' (length=6)
How come my default value is not being set?
The problem is that your database column does not allow null values for title.
You can allow them like this:
$table->string('title')->nullable()->default('');
Or even without the default to have it as NULL by default:
$table->string('title')->nullable();
Otherwise, you have to make sure your title is not null.
If you don't want to allow null values and convert it automatically to empty string, you can add a mutator like this to your model:
public function setTitleAttribute($title)
{
$this->attributes['title'] = is_null($title) ? '' : $title;
}
For more information: https://laravel.com/docs/5.6/eloquent-mutators
Because the 'title' key is in the provided array, it'll try to insert it: you should be able to insert null values.
You could use a mutator setTitleAttribute($val) method in your Model class, or simply unset the 'title' array key if the value is empty before inserting. You could also filter using collection helpers or array_filter to remove unset all null values.
I am using codeigniter and active record. I am selecting my data over WHERE with array. Any like this. But how can I insert tags '>' and '<'? It is possible?
$whereQuery['service.service_end_date'] = $start;
Thank you for replies.
This might be what you want:
Associative array method:
$array = array('name' => $name, 'title' => $title, 'status' => $status);
$this->db->where($array);
// Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
You can include your own operators using this method as well:
$array = array('name !=' => $name, 'id <' => $id, 'date >' => $date);
$this->db->where($array);
Source:
http://ellislab.com/codeigniter/user-guide/database/active_record.html
http://ellislab.com/codeigniter/user-guide/database/active_record.html
$whereQuery['service.service_end_date >'] = $start;
$whereQuery['service.service_end_date <'] = $start;
You can pass > < <> in CI where function
$this->db->where('field_name <', "Condition_value");
From Codeigniter page :
You can include an operator in the first parameter in order to control the comparison:
$this->db->where('name !=', $name);
$this->db->where('id <', $id);
// Produces: WHERE name != 'Joe' AND id < 45
I have a query as follows
$criteria1 = new CDbCriteria();
$criteria1->condition = 'id = 1';
$modelA=Table1::model()->find($criteria1);
I can pass it to a view and return the title and entry
$this->widget('bootstrap.widgets.TbBox', array(
title' => $modelA['title'],
'content' => $modelA['entry'] ));
Now I'd like to return a range of entries
$criteria2 = new CDbCriteria();
$criteria2->condition = 'id > 7';
$modelB=Table1::model()->findAll($criteria2);
(btw : I'm following a form as laid out here). I was expecting to be able to read the resulting array of values out as below, but ['title'] is now being seen as a undefined index (obviously I'm expecting to read this out in a loop but you get the point)
$this->widget('bootstrap.widgets.TbBox', array(
'title' => $modelB['title'][0],
'content' => $modelB['entry'][0]));
Where am I going wrong?
Thanks
No, the indexes should be specified in the different order: the number of a specific element first, then the name of the property. Additionally, it's better (=cleaner) to name the result of findAll so it'll show you (and any other reader) that it's a collection, not a single model:
$models = Table1::model()->findAll($criteria2);
// ...
$this->widget('bootstrap.widgets.TbBox', array(
'title' => $models[0]['title']
//...
));
But even that's not necessary if you use foreach (and you probably will):
foreach ($models as $model):
// ...
$this->widget('some.name', array(
'title' => $model['title']
);
endforeach;
In my model I have a relation() like this.
'notRelUser' => array(
self::HAS_MANY,
'LocationUser',
'location_id',
'condition' => 'notRelUser.status is null',
'on' => 'notRelUser.user_id = ' . Yii::app()->user->getId(),
'with' => array('parent_location'),
'select' => array('*', 'name AS canApply'),
),
and this
public $canApply;
In my controller I have this
$regions = Location::model()->with('notRelUser')->findAll();
$arrayCanApply = new CArrayDataProvider($regions);
I then am trying to print out the value of canApply in a widget for datagrid
<?php $this->widget('bootstrap.widgets.TbGridView', array(
'dataProvider'=>$arrayCanApply,
'columns'=>array(
array('name'=>'name', 'header'=>'Name'),
array('name' => 'canApply', 'value'=>'$data->canApply', 'header'=>'CanApply'),
),
));
But the column with canApply is empty.
I have also tried without the $data-> part.
How can I print this alias?
(I know the value of the alias i trivial, but I will change that later)
UPDATE:
I can get the value by using select in CDbCriteria - but I want to do it in relation.
This does work.
$criteria = new CDbCriteria;
$criteria->select = '("foobar") AS canApply';
$regions = Location::model()->with('notRelUser')->findAll($criteria);
but it seems odd that I have to create a $criteria on everytime
you need to declare can canApply as an attribute of the model
in your model decalare canApply as an attribute
public $canApply;
I also had the same problem. Try 'value'=>'$data->notRelUser->canApply'
instead of 'value'=>'$data->canApply'. Also, you need to declare attribute
public $canApply;
in your LocationUser model, not in Location model.