I have an api with one optional parameter called limit, which takes an integer and limits the number of documents returned from the api in a get request.
Implementing this limit is fine in my PHP application when it is a required parameter, but when its not specified as part of my get request, what is the best way to handle it?
is there for example, a way to define $limit and set it to all documents? (in pseudo code, $limit = none)
$list = $collection->aggregate( array( array('$match' => array( ... )),
'$project' => array ( ... )), '$limit' => intval($this->limit) ));
$this->limit //this is the optional input parameter
As you can see above, when the limit parameter is required it functions as required. Now when its ommitted, how can I keep the above code but specify no limit?
You could manually generate your where clause.
// Declare a where clause with your fixed conditions
$whereClause = array(array('$match' => array(...)), array('$project' => array(...)));
// Check if there's a limit
if($this->limit != 0)
array_push($whereClause, array('$limit' => $this->limit));
// Finally, call with the where clause we've generated above
$list = $collection->aggregate($whereClause);
Short answer No!
But, you can use an if/else condition like this:
<?php
if(intval($this->limit) != 0 ) {
$list = $collection->aggregate( array(
array('$match' => array( ... )),
array('$project' => array ( ... ))
array('$limit' => intval($this->limit))
);
));
} else {
$list = $collection->aggregate( array(
array('$match' => array( ... )),
array('$project' => array ( ... )),
);
}
?>
Related
Imagine this situation:
$component = array(
'type' => 'chimney',
'material' => 'stone'
);
What i would like to do is to add a key/value pair to this array, if a certain condition is met.
$hasMetrics = true;
$component = array(
'type' => 'chimney',
'material' => 'stone',
'metrics' => ($hasMetrics ? array('width' => 60, 'height' => 2000) : false)
);
While this could be used, it will always cause a key called 'metrics' in my array.
Of course, if i don't want that, i could use array_merge() to merge a second array with the first (the second being either an empty array or the desired key/value pair, depending on the condition).
But what i am longing to find out is if there is any way to define this array like above, while taking care of $hasMetrics, without the use of any other means (such as array_merge()) but purely in the actual (first and only) definition of this array.
Like this: (non-applicable, demonstrative example)
$component = array(
'type' => 'chimney',
'material' => 'stone',
($hasMetrics ? array('metrics' => array(
'width' => 60,
'height' => 2000
)) : false)
);
(This, as i understand it, would generate two keys (type and material and then create one keyless value that is, itself, an array containing a key (metrics) and another array as value.)
Can anyone show me some proper approach? Perhaps there is some kind of PHP function available, with special properties (such as list() which is capable of cross-assignment).
EDIT
Perhaps some more clarification is needed, as many answers point out ways to go such as:
Using a followup assignment to a certain key
Filtering the generated array after defining it
While these are perfectly valid ways to extend the array, but i am explicitly looking for a way to do this in one go within the one array definition.
Not with the array defenition itself. I would add it to the array if necessary:
if($hasMetrics) {
$component['metrics'] = array('width' => 60, 'height' => 2000);
}
$hasMetrics = true;
$component = array(
'type' => 'chimney',
'material' => 'stone',
);
if($hasMetrics){
$component['metrics'] = array('width' => 60, 'height' => 2000);
}
Try
$component = array(
'type' => 'chimney',
'material' => 'stone',
'metrics' => $hasMetrics ? array('width' => 60, 'height' => 2000) : ''
);
And after that
$component = array_filter( $component ); // remove if it has '' value
OR
$component = array(
'type' => 'chimney',
'material' => 'stone',
);
if($hasMetrics) {
$component['metrics'] = array('width' => 60, 'height' => 2000);
}
I'm trying to check my code, with count lines. But this code works very slow. how can i optimize this code? is there anyway to count?
$find = $conn_stok->distinct("isbn");
for($i=0;$i<=25; $i++) {
$isbn = $find[$i];
$countit= $conn_kit->find(array('isbn'=>$isbn))->count();
if($countit> 0){
echo "ok<br>";
} else {
echo "error<br>";
}
}
Looks like you are trying to do a simple count(*) group by in the old SQL speak. In MongoDB you would use the aggregation framework to have the database do the work for you instead of doing it in your code.
Here is what the aggregation framework pipeline would look like:
db.collection.aggregate({$group:{_id:"$isbn", count:{$sum:1}}}
I will let you translate that to PHP if you need help there are plenty of examples available.
It looks like you're trying to count the number of 25 top most ISBNs used, and count how often they have been used. In PHP, you would run the following queries. The first one to find all ISBNs, and the second is an aggregation command to do the grouping.
$find = $conn_stok->distinct( 'isbn' );
$aggr = $conn_kit->aggregate(
// find all ISBNs
array( '$match' => array( 'isbn' => array( '$in' => $find ) ) ),
// group those
array( '$group' => array( '_id' => '$isbn', count => array( '$sum' => 1 ) ) ),
// sort by the count
array( '$sort' => array( 'count' => 1 ) ),
// limit to the first 25 items (ie, the 25 most used ISBNs)
array( '$limit' => 25 ),
)
(You're a bit vague as to what $conn_stok and $conn_kit contain and what you want as answer. If you can update your question with that, I can update the answer).
No matter what I do I can't get it to respect the order I specify.
$this->paginate = array(
'Car' => array(
'limit' => 6,
'order' => array(
'Car.year' => 'desc'
),
'table' => 'cars'
)
);
Generated SQL:
SELECT `Car`.`id`, ... `Car`.`year`,... FROM `cars` AS `Car` WHERE 1 = 1 LIMIT 6
Turns out I was using a :sort in my url parameters. Once I took that out all was well :)
If you only have one item, you don't need/shouldn't use an array:
//one thing
var $order = "Model.field DESC";
//multiple things
var $order = array("Model.field" => "asc", "Model.field2" => "DESC");
(per this page)
Note too that virtual fields are ignored by default when paginating.
See "Control which fields used for ordering" in Cake 2.0 Pagination documentation.
Example:
$this->MyModel->virtualFields['count'] = 0;
$this->Paginator->settings = array(
'fields' => 'COUNT(id) AS MyModel__count',
'group' => ('MyModel.group_id'),
'order' => array('MyModel__count' => 'DESC'),
);
// IMPORTANT: pass sortable fields including the virtual field as 3rd parameter:
$log = $this->Paginator->paginate('MyModel', null, array('MyModel__count', 'id'));
Originaly posted on cakephp Q&A but i'll put it up here in hope of getting some answers.
I have a bunch of companies that has a status of 0 as default but sometimes get a higher status. Now i want to use the high status if exists but revert to 0 if not. i have tried a bunch of different approaches but i always get either only the ones with status 0 or the ones with the status i want, never giving me status if exists and 0 if not.
Gives me only the status i specify, not giving me the ones with status 0:
'Company' => array (
'conditions' => array (
'OR' => array(
'Company.status' => 0,
'Company.status' => $status,
)
)
)
Gives me only status of 0:
'Company' => array (
'conditions' => array (
'OR' => array(
'Company.status' => $status,
'Company.status' => 0
)
)
)
Status definition and retrieving data in code:
function getCountry($id = null, $status = null) {
// Bunch of code for retrieving country with $id and all it's companies etc, all with status 0.
$status_less_companies = $this->Country->find...
if ($status) {
$status_companies = $this->Country->find('first', array(
'conditions' => array(
'Country.id' => $id
),
'contain' => array(
'Product' => array (
'Company' => array (
'conditions' => array (
'OR' => array(
'Company.status' => $status,
'Company.status' => 0
)
)
)
)
)
)
}
// Mergin $status_less_companies and $status_companies and returning data to flex application.
}
I changed the name for the models for this question just to make more sense, people are generaly frighten away when i tell them i work with cakephp for my flex application. I guess the logic to this question doesn't make sense but trust me that it makes sense in my application.
Thanks!
Try
'Company' => array (
'conditions' => array (
'OR' => array(
array('Company.status' => 0),
array('Company.status' => $status),
)
)
)
In the cookbook it says to wrap the or conditions in arrays if they are pertaining to the same field
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#complex-find-conditions
I'm not sure to have understood what results you expect. If you want to retrieve all records having status = 0, plus let's say the one having status = 3, you could use an 'IN' instead of an 'OR'.
In Cake, you would write it like this:
$status = 3;
$conditions = array('Company.status' => array(0, $status));
You can also fetch record by using following method:
put values in an array
e.g. $arr=array(1,2);
$res = $this->Model->find('all', array(
'conditions' =>array('Model.filedname'=>$arr),
'model.id' => 'desc'
));
I hope you will find answer.
$this->loadModel('Color');
$colors = $this->Color->find('all', [
'conditions' => [
'Color.is_blocked' => 0,
'Color.is_deleted' => 0,
'OR' => [
[
'Color.isAdmin' => $user_data['id'],
],
[
'Color.isAdmin' => 0,
]
],
]
]);
I have a user model which gives me latest users as output. How can I limit the record to just output me 200 records instead of all the users in database?
According to the documentation, the second argument to the find() method is a $params array.
One of the possible values to pass in this array is a limit key. So you could do the following:
$users = $this->User->find('all', array('limit' => 200));
"i have it like array('limit' => 21, 'page' => 1) for paging 21 users in one page.. if i change the limit there to 200 then it paginates 200 users in one page only...in this case how to limit along with proper pagination?? – Anonymous May 14 '09 at 7:22"
yes you can use the cakePHP pagination helper as someone has mentioned. But there may be some cases where you want to do your own pagination or just limit the number of records retrieved per call. For what it's worth here's how I handled one such situation.
Say for example you want to retrieve a certain number of records per page, Then:
$start = 0; -> this is in order to start retrieving records starting from the first one. If you need to say for example, start from the 31st, then $start = 30;
So,
$start = 0;
$length = 20; // we are going to retrieve 20 records starting from the first record
And the code will be something like:
// To retrieve a number of Products per page
$products = $this->Product->find('all', array(
'order' => 'product_number ASC',
'limit' => $start.','.$length,
'recursive' => -1
)
);
Don't paginate with find().
Cake Pagination: http://book.cakephp.org/2.0/en/core-libraries/components/pagination.html
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
)
Limit * page = 200 set your values according to your comfortable view in pages. This might help
You can also try this out
$results = $this->Model->find('all',
array('limit'=>10,
'order'=>array('date DESC')));
open the model file of user and do as follows:
you will need to change the 'limit' property in the relationship variable named
var $hasMany = array( 'Abus' =>
array('className' => 'Abus',
'foreignKey' => 'user_id',
'dependent' => false, 'conditions'
=> '',
'fields' => '', 'order' => '', 'limit' => '200', 'offset'
=> '', 'exclusive' => '', 'finderQuery' => '',
'counterQuery' => '' ) );
OR you can also try this out...
in your users controller set the $paginate to like this.
var $paginate = array('limit' => 200);
The records will be limited to 200 now wherever you use paginate.