Get results in magento just like BETWEEN keyword in SQL - php

I've got this problem that I can't solve. Partly because I can't explain it with the right terms. I'm new to this so sorry for this clumsy question.
Below you can see an overview of my goal.
I'm using Magento CE 1.7.0.2
In SQL we have a keyword BETWEEN for filter the records between two values.
For Example: Select * from Mytable where rollnum BETWEEN 10 AND 100;
Like that I want to use in Magento
$_productCollection = Mage::getResourceModel('reports/product_collection')->addAttributeToSelect('*')->setOrder($choice, 'asc');
in the above i want to use that & that should work just like BETWEEN keyword in SQL..
Any Ideas....

$collection->addAttributeToFilter('start_date', array('date' => true, 'to' => $todaysDate))
->addAttributeToFilter('end_date', array(
array('date' => true, 'from' => $todaysDate),
array('null' => true)
)
Simple way, taking your problem :
$_productCollection->addAttributeToFilter(
array(
'attribute' => 'rollnum',
'in' => array(10, 100)
)
);

Related

MongoDB find query with $and $or and $nearSphere in php

After quite some trying out and web research I go crazy with this query. I want to build a query for 'Clubs' around a geo point (distance max 500 meters) in php on MongoDB.
But when I run query it ignores the distance limit and shows all clubs in database BUT sorted by distance.
Here is my dataset (2dsphere index geoLoc):
{"_id":ObjectId("547c649e30afe32c23000048"),"name":"Club Ritzz","category":"Club","category_list":[{"id":"191478144212980","name":"Night Club"}],"location":{"city":"Mannheim"},"geoLoc":{"type":"Point","coordinates":[8.473665839156,49.484065272756]}}
{"_id":ObjectId("547c649f30afe32c2300004a"),"name":"Das Zimmer Mannheim","category":"Club","category_list":[{"id":"191478144212980","name":"Night Club"}],"geoLoc":{"type":"Point","coordinates":[8.4709362941178,49.487260552592]}}
{"_id":ObjectId("547c64ab30afe32c23000063"),"name":"Nationaltheater Mannheim","category":"Arts/entertainment/nightlife","category_list":[{"id":"173883042668223","name":"Theatre"}],"geoLoc":{"type":"Point","coordinates":[8.4776534992592,49.48782606969]}}
{"_id":ObjectId("547c64a130afe32c2300004f"),"name":"SOHO Bar Club Lounge","category":"Club","category_list":[{"id":"191478144212980","name":"Night Club"},{"id":"164049010316507","name":"Gastropub"}],"geoLoc":{"type":"Point","coordinates":[8.4630844501277,49.49385193591]}}
{"_id":ObjectId("547c64a730afe32c2300005a"),"name":"Loft Club","category":"Club","category_list":[{"id":"191478144212980","name":"Night Club"},{"id":"176139629103647","name":"Dance Club"}],"geoLoc":{"type":"Point","coordinates":[8.4296300196465,49.484211928258]}}
And here my php code (updated Dec-2):
$qry = $pub->find(
array( '$and' =>
array(
array( 'geoLoc' =>
array('$nearSphere' =>
array('$geometry' =>
array('type'=>'Point',
'coordinates'=>
array(
floatval($sLon), floatval($sLat)
)
),
'maxDistance' => 500
)
)
),
array( '$or' =>
array(
array( 'name' => new MongoRegex("/.*club/i")),
array( 'name' => new MongoRegex("/.*zimm/i"))
)
),
array('$or' =>
array(
array('category_list.name' => 'Night Club'),
array('category_list.name' => 'Dance Club'),
array('category' => 'Club')
)
)
)
),
array('id' => 1, 'name' => 1, '_id' => 0)
);
Anyone know why the results are not limited to the specified maxDistance?
I found a similar issue on StackOverflow which outlines that one has to use radians for the maxDistance parameter.
See https://dba.stackexchange.com/questions/23869/nearsphere-returns-too-many-data-what-am-i-missing-am-i-wrong-is-it-a-bug-d
Also it is probably helpful if you'd test the query in mongo shell without using the PHP APIs first (just to see if the query is generally working and append '.explain()' to it to see what generally happens inside DB).

Paginate do not sort DESC

I can't display Agreements with agreement_number less than 7 and order it by agreement_number DESC.
I have read Pagination CakePHP Cook Book and can't find where my code is wrong. It display only less than 7, but always ASC. I have found similar question here, [that works],(CakePHP paginate and order by) and do not know why. Agreement.agreement_number is int(4).
$this->Agreement->recursive = 0;
$agreements = $this->Paginator->paginate('Agreement', array(
'Agreement.agreement_number <' => '7'
), array(
'Agreement.agreement_number' => 'desc'
)
);
$this->set('agreements', $agreements);
}
Exact cake version is 2.5.2.
... Where did you read that that was the correct syntax?
The paginate function's third parameter is for sorting (and I mean, within the table... with those down and up arrows).
List of allowed fields for ordering. This allows you to prevent
ordering on non-indexed, or undesirable columns.
You have the exact link used for documentation of the API, but you don't seem to be following it (like, from here and here)
$this->Paginator->settings = array(
'Agreement' => array(
'order' => array('Agreement.agreement_number' => 'desc')
)
);
$agreements = $this->Paginator->paginate('Agreement', array(
'Agreement.agreement_number <' => '7'));

zend framework 2 and doctrine query builder

I am trying to write a query using the doctrine query builder based on the parameters i am getting from an array.
Here's my array,
$query = array('field' => 'number,
'from' => '1',
'to' => '100',
'Id' => '2',
'Decimation' => '10'
);
The query that i am trying to write is,
select * from table where (number between 1 AND 100) AND (Id = 2) AND number mod 10 = 0
Here's where i stand now,
if (is_array($parameters['query'])) {
$queryBuilder->select()
->where(
$queryBuilder->expr()->between($parameters['query']['field'], $parameters['query']['from'], $parameters['query']['to']),
$queryBuilder->expr()->eq('Id', '=?1'),
$queryBuilder->expr()->eq($parameters['query']['field'],'mod 10 = 0')
)
->setParameter(array(1 => $parameters['query']['Id']));
}
I just cant wrap my head around this for some reason. Help !! anyone?
Not tested or anything, just directly typed into SO answer box:
$queryBuilder->select('table')
->from('My\Table\Entity', 'table')
->where($queryBuilder->expr()->andX(
$queryBuilder->expr()->between('table.number', ':from', ':to'),
$queryBuilder->expr()->eq->('table.id', ':id'),
))
->andWhere('MOD(table.number, :decimation) = 0')
->setParameters(array(
'from' => $parameters['query']['from'],
'to' => $parameters['query']['to'],
'id' => $parameters['query']['id'],
'decimation' => $parameters['query']['decimation']
));
It does not dynamically let you set which field to apply the where condition to. However, this is most likely a bad idea without whitelisting the values you want to allow. Once this is done a simple modification to the code above (just interpolate the value in place of number in the table.number string).
I kinda got it,
The main idea here was to use the andWhere clause. Multiple where clauses was what i wanted. and the mod operator that doctrine gives. Worked out pretty well. In between the requirement changed as well.

Count too slow in MongoDB with PHP

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).

addAttributeToFilter and OR condition in Magento's Collection

I'd like to select products depending on several criteria from different attribute.
I know how to user $collection->addAttributeToFilter('someattribute', array('like' => '%'));
But I'd like to use several attribute for OR condition.
Like:
$collection->addAttributeToFilter('someattribute', array('like' => 'value'));`
OR
$collection->addAttributeToFilter('otherattribute', array('like' => 'value'));`
To get products which either 'someattribute' OR 'otherattribute' set to 'value'
Is it possible?
yes it is.
$collection->addAttributeToFilter(
array(
array('attribute' => 'someattribute', 'like' => 'value'),
array('attribute' => 'otherattribute', 'like' => 'value'),
array('attribute' => 'anotherattribute', 'like' => 'value'),
)
);
In case you wish to use the same thing for addFieldToFilter function for collections that are not using the EAV, then you can using the following format:
$collection->addFieldToFilter(
array(
'someattribute',
'otherattribute',
'anotherattribute',
),
array(
array('like' => 'value'),
array('like' => 'value'),
array('like' => 'value'),
));
Another thing to look at to achieve 'OR" is:
->addFieldToFilter(
'type_id',
['in' => ['simple', 'configurable']]
)
For addAttributeToFilter:
$collections = Mage::getModel('sales/order')->getCollection()
->addAttributeToFilter('increment_id', array('in' => $sellerIncrementIds))
->addAttributeToFilter('status', ['in' => ['pending','pending_seller_confirmation']]);
addAttributeToFilter Conditionals
There are many operators in SQL and addAttributeToFilter will accept all of them, as long as you use the correct syntax. I've listed them all below and provided examples.
Equals: eq
This is the default operator and does not need to be specified. Below you can see how to use the operator, but also how to skip it and just enter the value you're using.
$_products->addAttributeToFilter('status', array('eq' => 1)); // Using the operator
$_products->addAttributeToFilter('status', 1); // Without using the operator
Not Equals - neq
$_products->addAttributeToFilter('sku', array('neq' => 'test-product'));
Like - like
$_products->addAttributeToFilter('sku', array('like' => 'UX%'));
One thing to note about like is that you can include SQL wildcard characters such as the percent sign, which matches any characters.
Not Like - nlike
$_products->addAttributeToFilter('sku', array('nlike' => 'err-prod%'));
In - in
$_products->addAttributeToFilter('id', array('in' => array(1,4,98)));
When using in, the value parameter accepts an array of values.
Not In - nin
$_products->addAttributeToFilter('id', array('nin' => array(1,4,98)));
NULL - null
$_products->addAttributeToFilter('description', array('null' => true));
Not NULL - notnull
$_products->addAttributeToFilter('description', array('notnull' => true));
Greater Than - gt
$_products->addAttributeToFilter('id', array('gt' => 5));
Less Than - lt
$_products->addAttributeToFilter('id', array('lt' => 5));
Greater Than or Equals To- gteq
$_products->addAttributeToFilter('id', array('gteq' => 5));
Less Than or Equals To - lteq
$_products->addAttributeToFilter('id', array('lteq' => 5));
Debugging The SQL Query
There are two ways to debug the query being executed when loading a collection in Magento.
/*
* This is the better way to debug the collection
*/
$collection->load(true);
/*
* This works but any extra SQL the collection object adds before loading
* may not be included
*/
echo $collection->getSelect();
Reference Link https://fishpig.co.uk/magento/tutorials/addattributetofilter/

Categories