How to use MySQL FORMAT with CakePHP? - mysql

I cant figure out why when I try to use FORMAT function to limit number of decimal places in the results of MySQL query it doesn't work. Here is how my code looks like:
...some other options to join tables with some conditions....
$options['fields'] = array(
'MetricSim.sim_id',
'MetricSim.metric_id',
'FORMAT(MetricSim.value,3) AS value'
);
$metrics_sims = $this->Sim->find('all', $options);
If I don't use the FORMAT function I get all of the results as expected. But when I try to use it I just don't get value field in my results (the rest of the fields are in place).

Why do you want to use FORMAT in your query? You can use a Helper to format your data in your view.
For example, in your controller class you add:
var $helpers = array('Number');
and in your view, you can format the value like:
$number->format($metric_sims['MetricSim']['value']);
(See NumberHelper class)

Related

Symfony Doctrine: Search in simple_array

I got values stored in my database column field as value1,value2,value3,value4, so a simple_array column.
So i'm using Doctrine to make a search using this:
$searchQuery = $this->getDoctrine()
->getRepository('AppBundle:Ads')
->createQueryBuilder('p')
->andWhere("p.vals <= :value2")
->setParameter('value2', $request->query->get('value2'));
->orderBy("p.creationtime", 'DESC');
So expecting value2 is in the 2nd position of a simple array like value1,value2,value3, how can i ask QueryBuilder to select the second value in the string?
I think this query try to get all the values in p.vals, results are not right, shound select just one.
How can I select eg. the 2nd value in p.vals?
I believe you cannot access nth item of an array column using pure Mysql since the data is serialized, in order to do it I'd create a simple function
public function getItemFromArray(array $array, $index)
{
return isset($array[$index]) ? $array[$index] : null;
}
And if you want to find item with condition use
array_filter()

Laravel 5.4 formatting result set

Can someone help me convert this query so that my result set is in different format?
$sessions = new Session();
$results = $sessions->where('session_status', $status)->where('application_period_id', (int) ApplicationPeriod::all()->last()->id)->get()->pluck('speaker_id');
$speakers = Speaker::whereIn('id', $results)
->with('session.audiancesession.audiances')
->with('session.subjectsession.subjects')
->with(['session' =>
function ($query) use($status) {
$query->where('session_status', '=', $status);
}])->orderBy('last_name')->get();
This is requested via Ajax(axios)... Now this is how result is formatted:
Obj->data(array of objects)->[0]->name
->address
->session(array of objects)
->[0]->time
->fee
My issue is that my session parameter is array and there can only ever be (1) so I don't need to to be an array and I would like to have object (json) instead.
Thank you!
You might have more success if you change your client-side code to work with an array of sessions each session having its speaker, that means your original query would be like
$sessions = Sessions::with([
'speaker', 'audiancesession.audiances', 'subjectsession.subjects'
])->where('application_period_id', (int) ApplicationPeriod::orderBy('id','DESC')->first())->get();
Note the order by -> first in the ApplicationPeriod makes it so you don't have to get all application periods from the database to memory.
Then your client side should handle an array of sessions.
You can transform the above slightly using to get a similar result to what you need:
$speakers = $sessions->map(function ($session) {
$speaker = collect($session->speaker->toArray());
$speaker->put('session', collect($session->toArray())->except('speaker'));
return $speaker;
})->orderBy('last_name','DESC');
Though I wouldn't guarantee the result here as I've not tested it on your (complex looking) data.

How can I find the datatypes of data fields using pdo?

try {
$q = $conn->prepare("DESCRIBE delete_subscriber");
$q->execute();
$tableFieldDS = $q->fetchAll(PDO::FETCH_COLUMN);
}
This code is to fetch the column name , so i am wondering are there any similar function i can use to get an array of the column data type? Thank you.

zend framework automatically alter queries

My database (mysql) tables use TIMESTAMP columns, and whenever I want them returned in a query, I want them to be queried as "UNIX_TIMESTAMP(columnname)".
How do you easily modify queries in zend framework to achieve this?
For example, the current code is:
select = $this->select();
$select->where('user_id = ?',$user_id);
return $this->fetchAll($select);
This eventually becomes:
select * from tablename where user_id = 42;
I want something that automatically finds the TIMESTAMP column and changes the resulting query to:
select user_id,name,unix_timestamp(created) where user_id = 42;
I know I can use a MySQL view to achieve this, but I'd rather avoid that.
Thanks.
RR
You should be able to specify the fields you want in the select using the $select->from() object.
Zend_Db_Select
You should end up with something like this.
$select = $this->select();
$select->from(
array('t' => 'tablename'),
array('user_id', 'name', 'UNIX_TIMESTAMP(created)')
);
$select->where('user_id = ?',$user_id);
return $this->fetchAll($select);
If you wanted to run an expression that doesn't have parenthese in the function, Use the Zend_Db_Expr() method to escape the query properly.

Use an sql "CONVERT" stored procedure in a Magento collection

I want to add a "CONVERT" stored procedure like this:
SELECT id, value, CONVERT(value, DECIMAL) AS ordred_value FROM test ORDER BY ordred_value;
to this collection query :
$collection = $this->getAssociatedProductCollection($product)
->addAttributeToSelect('*')
->addFilterByRequiredOptions()
->setPositionOrder()
->addStoreFilter($this->getStoreFilter($product))
->addAttributeToFilter('status', array('in' => $this->getStatusFilters($product)))
->addAttributeToSort('my_attribute', 'DESC');
for the purpose of ordering the associated products by my custom attribute "my_attribute" that have numeric values in text fields.
Thanks for help.
I'm not sure it's the bast solution, but you can do it like this:
<?php
$collection->getSelct()->columns(array('converted_value' => 'CONVERT(e.my_attribute, DECIMAL)'));
It will add a new column to result. Next sort the collection using it's select as above and the order method.