how to use Orderby in cakephp - cakephp

I am trying to order data in accordance with its priority...
But this query is not working for me....
I cannot figure it out where it went wrong..
please help me to solve this..
$admins = $this->xxx->find()
->select($fields)
->where($conditions)
->contain([
'yyy' => function ($q) {
return $q->autoFields(false)
->select(['id','name','login_url','priority'])
->order(['priority' => 'ASC']);
}
])
->all();

If the realtionship between xxx and yyy is belongsTo then you have to move the order() method outside the contain
$admins = $this->xxx->find()
->select($fields)
->where($conditions)
->contain([
'yyy' => function ($q) {
return $q->autoFields(false)
->select(['id','name','login_url','priority']);
}
])
->order(['yyy.priority' => 'ASC'])
->all();

array(
'conditions' => array('Model.field' => $thisValue), //array of conditions
'recursive' => 1, //int
//array of field names
'fields' => array('Model.field1', 'DISTINCT Model.field2'),
//string or array defining order
'order' => array('Model.created', 'Model.field3 DESC'),
'group' => array('Model.field'), // fields to GROUP BY
'limit' => n, //int
'page' => n, //int
'offset' => n, //int
'callbacks' => true //other possible values are false, 'before', 'after'
'having' => array('COUNT(Model.field) >' => 1), // fields to HAVING by
'lock' => true // Enable FORM UPDATE locking
)

Related

WP_Query - foreach array

In a WP_Query, i need some arrays to be dynamic, when a checkbox-group is checked.
The code so far is:
$args = array(
'post_type' => 'hold',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'hold_serie',
'value' => 'serie3',
'compare' => 'LIKE'
),
array(
'relation' => 'OR',
'options' => array()
),
),
);
$days = array('man', 'tir', 'ons');
foreach ($days as $value_day) {
$args['meta_query']['options'] = array(
'key' => 'hold_day',
'value' => $value_day,
'compare' => 'LIKE'
);
}
I have a checkbox group, which will make the same array as the $days-array().
What I'm hoping to achieve is, that the array with 'key' => 'hold_day' will be repeated three times, and the WP_Query will look at all the posts, that have either "man", "tir" OR "ons".
At this point, the WP_query only takes the post, with the last value in the array, in this case "ons".
If I delete "ons", so the array only have "man" and "tir", it only finds the posts, where "hold_day" = "tir".
What am I doing wrong?
You dose not need to use second part of the code.
You can use an array as the value of meta key, but in that case you need to use "IN" in compare field.
Your code should be
$args = array(
'post_type' => 'hold',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'hold_serie',
'value' => 'serie3',
'compare' => 'LIKE'
),
array(
'relation' => 'OR',
'key' => 'hold_day',
'value' => array('man', 'tir', 'ons'),
'compare' => 'IN'
),
),
);
Try the above code and let me know the result.
Thanks

Pagination is not working in cakephp

My code for controller:
public $paginate = array(
'paramType' => 'querystring',
'limit' => 3,
);
$this->paginate['Comment'] = array(
'conditions' => array('Comment.post_id' => $this->params['id']));
$this->set('comments',$this->paginate('Commant'));
When I do
pr($this->paginate['Comment'] = array(
'conditions' => array('Comment.post_id' => $this->params['id']))); exit;
The output is
Array
(
[conditions] => Array
(
[Response.claim_id] => 4
)
)
But instead of finding comment related to post it shows all post from db
Once I tried
pr($this->paginate['Comment'] = array(
'conditions' => array('Comment.id' => $this->params['id']))); exit;
And the Result was same
Array
(
[conditions] => Array
(
[Response.id] => 4
)
)
Can any one suggest me why pagination is not woking
Use
public $paginate = array(
'paramType' => 'querystring',
'limit' => 3,
);
in controller
$this->set('comments',$this->paginate('Response',
array('Response.claim_id' => $id)));
in your function
And define Paginator component in controller
You don't need to index your $this->paginate array with the model.
As you are using a Controller variable $this->paginate means that it doesn't need to be indexed using the model.

CakeDC Search and Tag plugin - search for multiple tags

Hopefully I'm missing something simple here. I'm using the CakeDC Search and Tags plugin for my cake (2.3.4) app.
Along with generic search by field functionality I want the user to be able to search by tags. I've almost got this working but the search will only display results if you search for a single tag not multiples. For example, if I add an article with the following tags - black, white, red. The article will only show in the search results if I search for a single tag (say, black) and not all 3, or even 2... What am I missing?
Heres my code:
Article.php model
class Article extends AppModel {
public $actsAs = array(
'Upload.Upload' => array(
'screenshot1' => array (
'fields' => array (
'dir' => 'dir'
),
'thumbnailMethod' => 'php',
'thumbnailSizes' => array(
'xvga' => '1024x768',
'vga' => '640x480',
'thumb' => '80x80'
),
),
),
'Search.Searchable',
'Tags.Taggable'
);
// Search plugin filters
public $filterArgs = array(
'title' => array('type' => 'like'),
'environment' => array('type' => 'like'),
'description' => array('type' => 'like'),
'error' => array('type' => 'like'),
'cause' => array('type' => 'like'),
'resolution' => array('type' => 'like'),
'live' => array('type' => 'value'),
'synced' => array('type' => 'value'),
'tags' => array('type' => 'subquery', 'method' => 'findByTags', 'field' => 'Article.id'),
array('name' => 'search', 'type' => 'query', 'method' => 'filterQuery'),
);
// This is the OR query that runs when the user uses the client side signle field search
public function filterQuery($data = array()) {
if(empty($data['search'])) { // search is the name of my search field
return array();
}
$query = '%'.$data['search'].'%';
return array(
'OR' => array(
'Article.title LIKE' => $query,
'Article.description LIKE' => $query,
'Article.error LIKE' => $query,
)
);
}
// Find by tags method
public function findByTags($data = array()) {
$this->Tagged->Behaviors->attach('Containable', array('autoFields' => false));
$this->Tagged->Behaviors->attach('Search.Searchable');
$query = $this->Tagged->getQuery('all', array(
'conditions' => array('Tag.name' => $data['tags']),
'fields' => array('foreign_key'),
'contain' => array('Tag')
));
return $query;
}
public $hasAndBelongsToMany = array(
'Category' => array(
'className' => 'Category',
'joinTable' => 'articles_categories',
'foreignKey' => 'article_id',
'associationForeignKey' => 'category_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
),
'Tag' => array('with' => 'Tagged')
);
Controller method
public function admin_advancedSearch() {
// Disable validation for this action
$this->Article->validate = array();
// For search plugin
$this->Prg->commonProcess();
// Set searched for details
$this->set('searchedFor', $this->passedArgs);
// If passed args are all empty
if ($this->passedArgs) {
if (empty($this->passedArgs['title']) AND
empty($this->passedArgs['environment']) AND
empty($this->passedArgs['description']) AND
empty($this->passedArgs['error']) AND
empty($this->passedArgs['cause']) AND
empty($this->passedArgs['resolution']) AND
empty($this->passedArgs['live']) AND
empty($this->passedArgs['synced']) AND
empty($this->passedArgs['tags'])) {
$this->Session->setFlash('Please enter at least one search criteria', 'flash_failure');
// Set this var for checks in view
$this->set('emptySeach', true);
} else {
$paginateConditions = $this->Article->parseCriteria($this->passedArgs);
$this->paginate = array('conditions' => array(
$paginateConditions),
'limit' => 10,
'order' => array('Article.modified' => 'DESC'));
$this->set('articles', $this->paginate());
// Count number of results
$count = 0;
foreach ($this->paginate() as $result) {
$count++;
}
$this->set('resultsCount', $count);
// Search was not empty - set flag for view
$this->set('emptySeach', false);
}
}
// Set layout
$this->layout = 'admin';
//debug($this->passedArgs);
}
All plugins are loaded successfully from bootstrap, searches work fine without tags. Searches with tags only work if one tag is entered....
*EDIT *
If I debug $query from the findByTags method I get this:
'SELECT `Tagged`.`foreign_key` FROM `knowledgebase`.`tagged` AS `Tagged` LEFT JOIN `knowledgebase`.`tags` AS `Tag` ON (`Tagged`.`tag_id` = `Tag`.`id`) WHERE `Tag`.`name` = 'kia, rio, red''
So it looks like its trying to find a single tag with all the searched for tags in its name. How can I make the WHERE part an IN?
For example:
WHERE `Tag`.`name` IN ('kia', 'rio', 'red')
Thanks
Use the "method" https://github.com/cakedc/search#behavior-and-model-configuration key her to pass the search args to a customized method.
The example here shows you exactly how this works https://github.com/cakedc/search#full-example-for-modelcontroller-configuration-with-overriding
public $filterArgs = array(
'some_related_table_id' => array('type' => 'value'),
'search'=> array('type' => 'like', 'encode' => true, 'before' => false, 'after' => false, 'field' => array('ThisModel.name', 'OtherModel.name')),
'name'=> array('type' => 'query', 'method' => 'searchNameCondition')
);
public function searchNameCondition($data = array()) {
$filter = $data['name'];
$cond = array(
'OR' => array(
$this->alias . '.name LIKE' => '' . $this->formatLike($filter) . '',
$this->alias . '.invoice_number LIKE' => '' . $this->formatLike($filter) . '',
));
return $cond;
}
Inside your custom method explode() the tags and make them an array so that CakePHP is using them as IN() or better (in can become slow) make it a chain of AND or OR.

Dropbdown list in Ascending Order in Cakephp

echo $form->input(
'country_id',
array(
'type' => 'select',
'label' => __('Country *', true),
'empty' => 'Select' ,
'order' => array('countries.name ASC')
)
);
Country list are not showing up in Ascending Order. Please anybody help me to find out an error or good way to show country list in ascending order.
You need to add order to your find query:
$countries = $this->Country->find('list', array(
'fields' => array('Country.id', 'Country.name'),
'order' => array('Country.name' => 'ASC')
))
For cakephp 3.* you can use this code;
$countries = $this->Country
->find('list',
[
'keyField' => 'Country.id',
'valueField' => 'Country.name',
'order' => array('Country.name' => 'ASC')
])
->toArray();

how to add condition to pagination in cakephp 1.3

how to convert this statment to pagination with condition rules
$comment = $this->Article->Comment->find('all',
array('conditions' =>
array('Comment.article_id' => $id, 'Comment.status' => 1)));
i do this but i get parce error
var $paginate = array(
'limit' => 5,
'page' => 1,
'order' => array('Comment.created'=>'desc'),
'conditions' => array('Comment.article_id' => $id, 'Comment.status' => 1)
);
$this->Article->Comment->recursive = 1;
this->set('comment', $this->paginate());
Follow the step-by-step instructions here.

Resources