How to specify a condition to retrieve data by radius (lat, lon)? - cakephp

In cakephp 2, I was able to use a virtualField for this, but seems impossible in 3. I have been struggling with this for two days without luck from the internet or the cakephp manual. I get no errors, but I do get a blank return.
My code in my controller looks like this:
if (isset($this->request->data['location']) && (isset($this->request->data['radius']))){
$radius = $this->request->data['radius'];
$location = $this->request->data['location'];
$address = $location; // Google HQ
$HttpSocket = new Client();
$geocode = $HttpSocket->get('http://maps.google.com/maps/api/geocode/json?address='.$address.'&sensor=false');
$geocode = $geocode->json;
if ($geocode['status'] == "OK"){
$lat = $geocode['results'][0]['geometry']['location']['lat'];
$lon = $geocode['results'][0]['geometry']['location']['lng'];
$R = 6371; // earth's mean radius, km
// first-cut bounding box (in degrees)
$maxLat = $lat + rad2deg($radius/$R);
$minLat = $lat - rad2deg($radius/$R);
// compensate for degrees longitude getting smaller with increasing latitude
$maxLon = $lon + rad2deg($radius/$R/cos(deg2rad($lat)));
$minLon = $lon - rad2deg($radius/$R/cos(deg2rad($lat)));
$conditions[] = ['Venues.lat' => "'BETWEEN '".$minLat."' AND '".$maxLat."'"];
$conditions[] = ['Venues.lon' => "'BETWEEN :'".$minLon."' AND :'".$maxLon."'"];
}
$this->paginate =[
'limit' => 10,
'order' => ['Quads.date' => 'asc'],
'conditions' => $conditions,
'contain' => [
'Performers' => ['Genres'],
'Users' => ['Profiles'],
'Venues' => ['fields' => [
'name',
'id',
'verified',
'address1',
'city',
'zip_code'], 'States'=>['Countries']],
'Categories',
'Likes' => ['Users' => ['Profiles']]]];
$quads = $this->paginate();

Impossible is (nearly) nothing. The old virtual fields concept is gone, right, the new ORM is flexible enough so that this isn't necessary anymore.
Your problem is that you are defining the conditions the wrong way, what you are doing there by specifying key => value sets, is creating ordinary operator conditions, where the value is going to be escaped/casted according to the column type. In case you really don't receive any errors, I'd assume that the lat/lan columns are of a numeric type, so your BETWEEN ... strings do end up as numbers, and the conditions will look something like
Venus.lat = 0 AND Venus.lon = 0
Also note that you are creating a nested array, ie
[
['keyA' => 'value'],
['keyB' => 'value']
]
and while this works, you may run into further problems in case you're not aware of it, so you'd better stick with
[
'keyA' => 'value',
'keyB' => 'value'
]
unless there's actually a technical reason to use nested conditions.
tl;dr use expressions
That being said, you can use expressions to build the proper conditions, like
$conditions[] = $this->Quads->Venues
->query()->newExpr()->between('Venues.lat', $minLat, $maxLat);
$conditions[] = $this->Quads->Venues
->query()->newExpr()->between('Venues.lon', $minLon, $maxLon);
This will safely create proper conditions like
Venus.lat BETWEEN a AND b AND Venus.lon BETWEEN x AND Y
Note that it is advised to create the expressions via the table that holds the columns (VenuesTable in this case), as you'd otherwise have to manually specify the column type (see the fourth argument of QueryExpression::between()) in order for the correct casting/escaping to be applied!
See also
Cookbook > Database Access & ORM > Query Builder > Advanced Conditions
Cookbook > Database Access & ORM > Query Builder > Using SQL Functions
API > \Cake\Database\QueryExpression::between()

Related

Counting and categorising instances of certain fields

I'm currently writing a survey style app that has some models:
Assessments
Recommendations
An assessment has many recommendations and is joined by the assessments_recommendations table, and I store data in the join table which are effectively answers.
One such answer is user impact. This field is an integer value between 0 and 10 and is different for each assessment->recommendation.
What I want to be able to do is send a count and categorisation of that field into a view so that I can chart it using chart.js. For example, I would like:
0-3 = Low
4-7 = Moderate
8-10 = High
As far as I can tell, I need to pass something along the lines of:
$counts [4, 6, 8]
$legend ['Low', 'Moderate', 'High']
So in the above example, 4 assessment->recommendations are classed as low, 6 are moderate, 8 are high.
Does anyone have any advice on how to do this in my controller? I've been reading up on collections but I'm not sure that is the correct way of doing this. I had issues as my data is stored in the _joinData part of the array and I couldn't figure out how to access it.
Any advice would be much appreciated.
Thanks!
Edit 1
This is the controller code I have been playing around with to get an initial collection working. The col variable passes through nicely and I can see this in the view. I get 'unknown getter' error on the join data line though. It isn't entirely clear to me from the docs what variables are what in the example in the book, so I've been very much trying every combo I can think of to try and get it to work before even trying to move on with the complete scenario.
public function view($id = null)
{
$this->loadModel ('Assessments');
$this->loadModel ('Recommendations');
$query = $this->Assessments->find('all', [
'conditions' => ['Assessments.id =' => $id],
'contain' => ['Recommendations']
]);
$assessment = $query->first();
$collection = new Collection($assessment->ToArray());
$countHigh = $collection->countBy(function ($assessment) {
return $assessment->_joinData->_user_impact > 7 ? 'High' : 'Error';
});
$this->set('assessments', $assessment);
$this->set('col', $collection);
$this->set('user_impact_high', $countHigh);
}
Edit 2
So I'm testing this some more. Trying to simplify it. Even using the groupBy function in it's simple form is failing. The code below generates the following error.
public function view($id = null)
{
$this->loadModel ('Assessments');
$this->loadModel ('Recommendations');
$query = $this->Assessments->find('all', [
'conditions' => ['Assessments.id =' => $id],
'contain' => ['Recommendations']
]);
$assessment = $query->first();
$collection = new Collection($assessment->ToArray());
$test = $collection->groupBy('client_id');
$this->set('assessments', $assessment);
$this->set('col', $collection);
$this->set('test', $test);
}
Error:
Cannot use object of type Cake\I18n\FrozenTime as array

CakePHP 3 - unable to generate a query with WHERE...OR conditions

CakePHP 3.7
I'm trying to generate a query which uses a WHERE...OR pattern. The equivalent in MySQL - which executes and gives the results I want is:
SELECT * FROM groups Groups WHERE (regulation_id = 1 AND label like '%labelling%') OR (id IN(89,1,8,232,228,276,268,294));
I've read the Advanced Conditions (https://book.cakephp.org/3.0/en/orm/query-builder.html#advanced-conditions) part of the documentation but can't generate that query.
Assume the Table class is Groups I have this:
$Groups = TableRegistry::getTableLocator()->get('Groups');
$groups_data = $Groups->find('all')->where(['regulation_id' => 1);
$groups_data = $groups_data->where(['label LIKE' => '%labelling%']);
This produces the first segment of the WHERE statement, i.e.
SELECT * FROM groups Groups WHERE (regulation_id = 1 AND label like '%labelling%')
However I can't see how to attach the OR condition, especially since orWhere() is deprecated.
So I've tried this - which is even given as an example in the docs:
$in_array = [89,1,8,232,228,276,268,294]; // ID's for IN condition
$groups_data = $groups_data->where(['OR' => ['id IN' => $in_array]]);
But this just appends an AND to the inside of my existing SQL:
SELECT * FROM groups Groups WHERE (regulation_id = 1 AND label like '%labelling%' AND id IN(89,1,8,232,228,276,268,294);
Which does not yield the correct results as the syntax isn't what's required to run this query.
How do you "move out" of the WHERE and append an OR condition like in the vanilla query?
I made several attempts using QueryExpression as per the docs, but all of these produced PHP Fatal Errors saying something to do with the Table class - I doubt this was on the right lines anyway.
"moving out" is a little tricky, you have to understand that internally the conditions are pushed into a \Cake\Database\Expression\QueryExpression object which by default uses AND to concatenate the statements, so whatever you push on to that, will be added using AND.
When you create OR statements, being it implicitly with the shown nested array syntax, or explicitly by using the expression builder, this creates a separate, self-contained expression, where its parts are being concatenated using OR, it will compile itself (and since there's only one condition, you don't see any OR's), and the result will be used in the parent expression, which in your case is the main/base expression object for the queries where clause.
Either pass the whole thing at once (being it via array syntax or expressions), eg:
$groups_data->where([
'OR' => [
'AND' => [
'regulation_id' => 1,
'label LIKE' => '%labelling%'
],
'id IN' => $in_array
]
]);
and of course you could build that array dynamically if required, or, if you for some reason need to use separate calls to where(), you could for example overwrite the conditions (third parameter of where()), and include the current ones where you need them:
$groups_data->where(
[
'OR' => [
$groups_data->clause('where'),
'id IN' => $in_array
]
],
[],
true
);
I know this issue is old but maybe someone is looking. Here is my solution:
protected $_hardValues= array(
'company_id' => $company_from_session;
);
function beforeFind($event=null, $query = null, $options = null, $primary = true){
$conds = [];
$columns = $this->getSchema()->columns();
foreach( $this->_hardValues as $field => $value){
if( !is_null($value) && in_array($field, $columns) ){
$conds[$this->_alias . '.' . $field] = $value;
}
}
if( empty( $conds)) return true;
$where = $query->clause('where'); //QueryExpression object;
if( empty( $where)){
$query->where($conds);
}else{
$where->add($conds);
}
}
As of CakePHP 4.x, the documented way of doing this is:
$query = $articles->find()
->where([
'author_id' => 3,
'OR' => [['view_count' => 2], ['view_count' => 3]],
]);
See documentation

cakephp sort link not working

Can't make sort links work. (concrete or virtual fields).
Vitual fields for my sum() field on this action:
$this->Qca->virtualFields['comps'] = 'Sum(CASE WHEN Qca.qca_tipcode = 1 THEN 1 END)';
$this->Qca->virtualFields['production'] = 'Sum(qca_end - qca_start)';
$this->Qca->virtualFields['idle'] = 'Sum(Qca.qca_durend)';
My find(), works fine:
$hoursvalues = $this->Qca->find('all', array('conditions' => $conditions,
'fields' => array('Qca.dir_id', 'Qca.name', 'Sum(CASE WHEN Qca.qca_tipcode = 1 THEN 1 END) AS Qca__comps', 'Sum(qca_end - qca_start) as Qca__production', 'Sum(Qca.qca_durend) as Qca__idle'),
'group' => array('Qca.dir_id')
)
);
and then:
$this->paginate('Qca' );
$this->set('hoursvalues', $hoursvalues);
What extra settings does $this->paginate('Qca' ); needs? Please note I have all data I need via find().
What is it I'm missing that sorting does not work for either concrete or virtual fields?
Thansk a lot!
Carlos
Part of your problem is the following:
$this->paginate('Qca');
$this->set('hoursvalues', $hoursvalues);
$this->paginate() returns an array with sorted values. What you need to do is specify your extra settings in $this->paginate array and then
$this->set('hoursvalues', $this->paginate('Qca'));
For your other fields, making them virtualFields will make them easier to work with.

cakephp saveMany using $fieldList (no form)

I have this $data array: (built on a shell, not a form)
(debugged here)
array(
(int) 0 => array(
(int) 0 => 's511013t',
(int) 1 => 'id3422',
(int) 2 => '1'
),
(int) 1 => array(
(int) 0 => 's511013t',
(int) 1 => 'id3637',
(int) 2 => '1'
)
)
And using saveMany :
$this->Dir->saveMany($data, array( 'validate' => 'false', 'fieldList' => array('name','dir_dataname', 'project_id')));
Saving fails with no error.
I'm not sure if my $data array is well formatted, (I'm confused whether it should have another level) I built it from sql selects, etc. However it does contain all info I need saved, single model.
I'm running all this from a Shell and it does work to save a single record provided the field names everytime:
// this works
$this->Dir->save(array('name' => $data[0][0], 'project_id' => $data[0][2], 'dir_dataname' => $data[0][1]));
Already read Saving your data, and I'd really like to use saveMany and a fieldList due to my custom $data format. (I wouldn't like to have to insert field names on my $data).
(no sql_dump to show since is pretty cumbersome to get it from a shell task)
I've spent all evening trying to figure it out, can you point me in the right direction, Please?
IMHO, the keys in each arrays are not valid fields in your database table. They should represent the same name as your table field.
When you build the array from sql, the output should look like these - an associative array:
array(
(int) 0 => array(
(string) name => 's511013t',
(string) dir_dataname => 'id3422',
(string) project_id => '1'
),
(int) 1 => array(
(string) name => 's511013t',
(string) dir_dataname => 'id3637',
(string) project_id => '1'
)
)
Cake2.0 Docs
$this->Dir->saveMany($data);
You can get the log via
debug($this->Dir->getDataSource()->getLog());
It looks as if you are using fieldList incorrectly. fieldList is a list of fields that are to be whitelisted for saving to the database, not a "mapping" like you are using.
You need to specify field => value pairs in the array for each record, not numerical indexes. I may be wrong, but I've never seen that and it doesn't look to be that way according to docs.

Should I use more find in this case?

i have two controllers
Sections_controller.php
Articles_controller.php
Section model hasmany Article...
i want to fetch articles In the form of blocks like all news sites..every block have section name with links to the articles within this section..so i use this code......
The First block
$block1=$this->Article->find('all',
array(
'limit' => 4, // just fetch 4 articles
'order' => array('Article.created'=>'DESC'),
'conditions' => array('Section_id' => 87)
)
);
// set the section for the view
$this->set(compact('block1'));
The second block
$block2=$this->Article->find('all',
array(
'limit' => 4, // just fetch 4 articles
'order' => array('Article.created'=>'DESC'),
'conditions' => array('Section_id' => 88)
)
);
// set the section for the view
$this->set(compact('block2'));
and etc....
anyone have the best method in this task without Repetition find code..
notice..i cant pass $id in the function because articles must display when request site index example( www.newssite.com)
Any find(s) should be done in the Model, not the controller - this follows the MVC structure as well as the "fat models, skinny controllers" mantra, which helps keep with the MVC idea.
This is not only the way it "should" be done, but it will also allow you to have the code in just one place:
//in the Article model
function getArticlesBySection($id) {
$articles = $this->find('all', array(
'limit' => 4,
'order' => array('Article.created'=>'DESC'),
'conditions' => array('Section_id' => $id)
));
return $articles;
}
//in the Articles controller
$block1 = $this->Article->getArticlesBySection('87');
$block2 = $this->Article->getArticlesBySection('88');
$this->set(compact('block1', 'block2'));
The above should work just fine for what you want to do, but there is always a lot you can do to improve upon it - like setting it up to be a lot more flexible by accepting an array of options:
//in the Article model
function getArticles($id, $opts = null) {
$params = array();
//limit
$params['limit'] = 100; //catchall if no limit is passed
if(!empty($opts['limit'])) $params['limit'] = $opts['limit'];
//order
$params['order'] = array('Article.created'=>'DESC');
if(!empty($opts['order'])) $params['order'] = $opts['order'];
//conditions
$params['conditions'] = array();
if(!empty($opts['sections'])) array_push($params['conditions'], array('Section_id'=>$opts['sections']));
$articles = $this->find('all', $params);
return $articles;
}
//in the Articles controller
$opts = array('limit'=>4, 'sections'=>array('87'));
$block1 = $this->Article->getArticles($opts);
$opts['sections'] = array('88');
$block2 = $this->Article->getArticles($opts);
I'm sure there are things that can be done to make this more lean...etc, but it's how I like to write it for ease of use and readability, and at least gives you a start on how to think of model methods, and the ability to use and reuse them for different purposes.
You can accomplish this with a straight mysql query, but I'm not sure how you would fit it into a cake model->find function. You can do something like this:
$articles = $this->Article->query("SELECT * FROM articles a WHERE (SELECT COUNT(*) FROM articles b WHERE a.Section_id = b.Section_id AND a.created < b.created) < 4 ORDER BY a.Section_id, a.created DESC");
/* if you look at the results, you should have the 4 latest articles per section.
Now you can loop through and set up an array to filter them by section. Modify to fit your needs */
foreach($articles as $article) {
$results[$article['Article']['Section_id']][] = $article;
}
$this->set('results',$results);

Resources