I have a field in database. It's type is enum and it looks like
enum('NO ANSWER', 'ANSWERED', 'BUSY').
I need to put this values into dropdown. How can I write query in cakephp?
I tried:
$result = TableRegistry::get('Calls')->find('list', ['valueField' => 'disposition'])->distinct('disposition')->toArray();
But it returns
[
(int) 1 => null,
(int) 77 => '',
(int) 64 => 'NO ANSWER',
(int) 65 => 'ANSWERED',
(int) 72 => 'BUSY'
]
but I need something like this:
[
(int) 1 => 'NO ANSWER',
(int) 2 => 'ANSWERED',
(int) 3 => 'BUSY'
]
I need to put this values into dropdown
Unless the enum values are going to change frequently (and if the are, why would you use an enum..) just put the array of data you need somewhere:
$options = [
'NO ANSWER' => 'NO ANSWER',
'ANSWERED' => 'ANSWERED',
'BUSY' => 'BUSY'
];
And then use it:
echo $this->Form->select('field', $options);
Note that the key in $options is what will be submitted, the value is what will be displayed. More info about the select method is in the documentation.
I found this answer somewhere on SO, but I couldn't find it again. You can do this:
$cols = $this->Model->query("show columns from table_name like 'enum_column_name'")
$enum = explode(',', substr(str_replace(array("'", "(", ")"),'',$cols[0]['COLUMNS']['Type']), 4));
$options = array_combine($enum, $enum);
Then in your form, you can use the end of AD7six's answer and add:
echo $this->Form->select('field', $options);
The problem is that the values of enum are defined in the create table, they are not a piece of data available when you query your table's data. How can I get enum possible values in a MySQL database? SO topic describes how to get the values of the enum through a php code. Just make sure that you reassign the keys for the enum values so that the keys start from 1, and not from 0 (0 stands for empty value).
Related
I want to insert values to database each time when values are submitted.
These are the post values from the form.
$sFloorKey = $_POST['floorname']; // int value : eg - 5
$aRoomName = $_POST['roomname']; //array contaning multiple values
$iRoomType = $_POST['roomtype']; //array contaning multiple values
$iPostID = $_POST['postid']; // int value : eg - 44
The wp query performed ,
$wpdb->insert('bs_room_types', array(
'postid' => $iPostID ,
'sfloorname' => $sFloorKey,
'aroomname' => $aRoomName,
'aroomtypes' => $iRoomType,
));
The $sFloorKey and $iPostID are getting inserted but the array values not.
Please help out here!
As per the help of #MilanChheda its working perfectly now.
Before inserting i have serialized the values.
$iPostID = $_POST['postid'];
$sFloorKey = $_POST['floorname'];
$aRooms = serialize($_POST['roomname']);
$iRoomType = serialize($_POST['roomtype']);
$wpdb->insert('bs_room_types', array(
'postid' => $iPostID,
'sfloorname' => $sFloorKey,
'aroomname' => $aRooms,
'aroomtypes' => $iRoomType,
));
I have two related tables. For example,
tbl_one
id
name
tbl_second
id
id_tblone(this is fk)
name
For example:
tbl_one
id: 1
name: input one
tbl_second
id: 1
id_tblone: 1
name: data one
id: 2
id_tblone: 1
name: data two
Select will show:
input one
input two
I want to use Kartik's select in a form that will save new data in tbl_second. So I need Select2 to select id_tblone (or id from tbl_one) and his according name. User needs to select, let's say proper category (from first table - I have fk that relates those two tables) and add some new data under that category in second table.
What would be proper way to do this?
Edit: i have managed so far to show proper names under proper id_tblone, but it saves data with value null in id_tblone column in my second table
In controller:
$query = array();
$query = (new \yii\db\Query())
->select(['id', 'name'])
->from('tbl_one')
->leftJoin('tbl_second', 'tbl_second.id_tblone = tbl_one.id')
->all();
in view:
$data = ArrayHelper::map($query,'name', 'id');
echo Select2::widget([
'name' => 'newname',
'data' => $data,
'pluginOptions' => [
'allowClear' => true
],
]);
I am trying to pull record from a table using the following code
$userId = Yii::$app->user->id;
$lists = PromoLists::findAll(['user_id' => $userId, 'list_type' => 'custom']);
which outputs a query like below
select * from promo_lists where user_id ='$userId' and list_type='custom'
But i am unable to find any thing in the documentation that would help me achieve it with the following condition.
select * from promo_lists where user_id ='$userId' and list_type='custom' and status!='deleted'
as the status is an ENUM field and there are 4 different status
'active','pending','rejected','deleted'
currently i used the following approach
PromoLists::findAll(['user_id' => $userId, 'list_type' => 'custom', 'status'=>['active','pending','rejected']]);
which outputsthe following query
select * from promo_lists where user_id ='$userId' and list_type='custom' and status in ('active','pending','rejected')
which somehow achieves the same thing but this query would need to be edited every time when there is a new status type added to the table column status.
i know i can do this by using PromoLists::find()->where()->andWhere()->all()
but how to check with != / <> operator using findAll().
Simply like this:
PromoLists::find()->where(['and',
[
'user_id' => $userId,
'list_type' => 'custom',
],
['<>', 'status', 'deleted'],
])->all();
Using operator format in condition
http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html#operator-format
PromoLists::find()
->andWhere([
'user_id' => $userId,
'list_type' => 'custom',
['!=', 'status', 'deleted']
])
->all();
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 a BD that contains people with day and month fields, like so:
person1 (day = 5; month = 3)
person2 (day = 2; month = 12)
I have to perform a find between 2 dates, for example, I need all people between 01/03 and 01/06 (day/month) but I don't know how to perform that.
I tried using separate conditions, like this:
$conditions['People.day >='] = dayA;
$conditions['People.month >='] = monthA;
$conditions['People.day <='] = dayB;
$conditions['People.month <='] = monthB;
But, that's not correct because it finds day and month, I mean, it finds People between monthA and monthB and People between dayA and dayB, instead, what I need is people between dayA/monthA and dayB/monthB
I suppose I must do some kind of a JOIN, but I'm lost here, I looked some information but I don't know where to start.
updated info:
ok, I'm using this
Array
(
[People.month_day BETWEEN ? AND ?] => Array
(
[0] => 01/02
[1] => 28/02
)
)
but I get people like this:
1/1
2/1
10/1
11/1
12/1
13/1
20/1
21/1
1/2
what's wrong? do you need more code? I'm using this to retrieve results:
A paginate:
public $paginate = array('People'=>array(
'limit' => 16,
'order' => 'People.month, People.day ASC'
));
In your People model
public $virtualFields = array(
'month_day' => 'CONCAT(People.month, "-", People.day)'
// 'month_day' => 'CONCAT(People.day, "/", People.month)'
);
then add in your controller
$options = array(
'conditions' => array(
'Post.month_day BETWEEN ? AND ?' => array('01-03','01-06')
// 'Post.month_day BETWEEN ? AND ?' => array('03/01','06/01')
)
);
$posts = $this->Post->find('all',$options);
It would be best to alter your table. Use DATE field and your SQL query would be:
SELECT *
FROM dbname.People
WHERE People.date BETWEEN '1999-03-01' AND '1999-06-01';