How to addAttributeToFilter? - search

I am trying to get Collection of all available products in Magento & Filter that collection
Here is my code:
$searcher = Mage::getModel('catalog/product')->getCollection();
$searcher->addAttributeToSelect('name');
echo count($searcher);
$searcher->addAttributeToFilter('name',array('like' => 'paper'));
$searcher->load();
echo count($searcher);
Now first time it gives count 745(FOR ALL PRODUCTS) but after filtering it still shows 745.

EDIT: This works for me:
$searcher = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('name')
->addAttributeToFilter('name',array('eq' => 'paper'));
$searcher->load();
echo count($searcher);

Related

How to get all the matching values from '$in' operator in mongoose

I have multiple checkboxes for different categories of blogs -
And what I want to achieve is that when I select some categories and click on filter, the specified selected blogs would be shown. I used query string parameters or URL parameters to send all the selected checkbox values to the nodejs backend -
query is an array containing all the selected categories
const response = await axios.get(`http://localhost:8000/blog/all?categories=${query}`)
And in the backend -
const cat = req.query.categories;
const all = await blogModel.find({ category: { $in: cat } });
I am passing the cat, which again consists of all the selected categories from the frontend, to $in to find all the matching blogs.
But the issue I am facing is that I am not getting matching blogs, say when I select the 'Science' checkbox and click on the filter I am able to get all the blogs having 'Science' as a category. But when I select say 'Science' & 'Food', I am getting an empty array as output even though I do have blogs of both categories in my MongoDB.
Backend console log of cat when I select 'Science' category -
And when I select 'Science' & 'Food' -
I get an empty array as output instead of all the blogs of 'Science' & 'Food' categories.
To summarize , when i select more than one categories i am getting an empty array instead of the blogs of the selected categories.And when i select only one category then i am able to get the selected blogs.It's not working for multiple categories
I am sure I am missing out on something but don't know what to google to get correct results. I also went through similar StackOverflow questions but I was not able to wrap my head around what needs to be done. I am building a simple blog website for my portfolio & thought of adding this 'filter by category' feature so that I would get to learn on how to filter values from MongoDB using mongoose. Please help me resolve this issue. Thank You.
Edit 1 - This is an example of a document from my collection
Also 'console.log(req.query.categories)' outputs this when i select 'Science' & 'Food' from the above checkbox -
I think you didnt path data as array to mongo query
first split by , and then pass to query
const cat = req.query.categories;
cat = cat.split(",")
const all = await blogModel.find({ category: { $in: cat } });
Yes there seems no issue in your query, make sure you are passing right data to backend like you saved "food" as category in database and searching for "Food" it will return empty array as it is case sensitive.
db.Posts.find({category: { $in:["Food","Gaming"]}})
You can also try this way to fetch
db.Posts.aggregate([{$match:{category: {$in:["cat","dog"]}}}])
const cat = req.query.categories;
var splitcat = cat .split(",");
db.Posts.find({category: { $in:splitcat }})

limit is not working in query cakephp 3

I am using the following query to show list of data, but here limit is not working.
$query = $this->Bookings->find('all')
->where(['Bookings.user_id' => $id])
->contain(['Services'])
->limit(10)
->orderDesc('booking_date');
$this->set('bookings', $this->paginate($query));
$this->set('_serialize', ['bookings']);
but, I am not getting the list of 10 data in each page.
Perhaps it is better to use the $paginate property and then use the maxLimit
See: http://book.cakephp.org/3.0/en/controllers/components/pagination.html#limit-the-maximum-number-of-rows-per-page

Filter resources by template variable value with MODx Wayfinder

I have a site that uses Wayfinder to display the latest 3 entries from an Articles blog. Now, I want to only consider those blog entries that are tagged Highlights.
My original Wayfinder call looks like this, nothing spectacular:
[[!Wayfinder? &startId=`296` &level=`1`
&outerTpl=`emptyTpl`
&innerTpl=``
&rowTpl=`thumbnails_formatter`
&ignoreHidden=`1`
&sortBy=`menuindex`
&sortOrder=`DESC`
&limit=`3`
&cacheResults=`0`
]]
as Articles tags are managed via the articlestags TV, I thought that a &where might do the trick, but with no luck yet:
&where=`[{"articlestags:LIKE":"%Highlights%"}]`
does not yield anything. As a sanity check, I tried [{"pagetitle:LIKE":"%something%"}], which worked. Obviously, the problem is that articlestags is not a column of modx_site_content, but I'm not sure about how to put the subquery.
SELECT contentid
FROM modx_site_tmplvar_contentvalues
WHERE tmplvarid=17
AND value LIKE '%Highlights%'
Gave me the right IDs on the sql prompt, but adding it to the Wayfinder call like this gave an empty result again:
&where=`["id IN (SELECT contentid FROM modx_site_tmplvar_contentvalues WHERE tmplvarid=17 AND value LIKE '%Highlights%')"]`
Any ideas on how to achieve this? I'd like to stay with Wayfinder for consistency, but other solutions are welcome as well.
You can just use pdomenu (part of pdoTools) instead Wayfinder
[[!PdoMenu?
&startId=`296`
&level=`1`
&outerTpl=`emptyTpl`
&innerTpl=``
&rowTpl=`thumbnails_formatter`
&ignoreHidden=`1`
&sortBy=`menuindex`
&sortOrder=`DESC`
&limit=`3`
&cacheResults=`0`
&includeTVs=`articlestags`
&where=`[{"TVarticlestags.value:LIKE":"%filter%"}]`
]]
Take a peek at some of the config files [core/components/wayfinder/configs ] - I have not tried it, but it looks as if you can run your select query right in the config & pass the tmplvarid array to the $where variable.
A little playing around led me to a solution: I needed to include the class name (not table name) when referring to the ID:
&where=`["modResource.id IN (SELECT contentid FROM modx_site_tmplvar_contentvalues WHERE tmplvarid=17 AND value LIKE '%Highlights%')"]`
a small test showed that even a simple
&where=`["id = 123"]`
does not work without modResource..
A look at wayfinder.class.php shows the following line, which seems to be the "culprit":
$c->select($this->modx->getSelectColumns('modResource','modResource'));
This method aliases the selected columns - relevant code is in xpdoobject.class.php. The first parameter is the class name, the second a table alias. The effect is that the query selects id AS modResource.id, and so on.
EDIT: final version of my query:
&where=`["modResource.id IN (
SELECT val.contentid
FROM modx_site_tmplvars AS tv
JOIN modx_site_tmplvar_contentvalues AS val
ON tv.id = val.tmplvarid
WHERE tv.name = 'articlestags' AND (
val.value = 'Highlights'
OR val.value LIKE 'Highlights,%'
OR val.value LIKE '%,Highlights'
OR val.value LIKE '%,Highlights,%'
)
)"]`
I don't claim this query is particularly efficient (I seem to recall that OR conditions are bad). Also, MODx won't work with this one if the newlines aren't stripped out. Still, I prefer to publish the query in its well-formatted form.
I used snippet as a parameter for the includeDocs of wayfinder, In my case it was useful because I was need different resources in menu depend on user browser (mobile or desktop)
[[!Wayfinder?
&startId=`4`
&level=`1`
&includeDocs=`[[!menu_docs?&startId=`4`]]`
&outerTpl=`home_menu_outer`
&rowTpl=`menu_row`
]]
and then menu_docs snippet
<?php
if (empty ($startId))
return;
if (!isMobileDevice())
return;
$query = $modx->newQuery('modResource');
$query->innerJoin('modTemplateVarResource','TemplateVarResources');
$query->where(array(
'TemplateVarResources.tmplvarid' => 3,
'TemplateVarResources.value:LIKE' => 'yes',
'modResource.parent' => $startId,
'modResource.deleted' => 0,
'modResource.published' => 1,
'modResource.hidemenu' => 0
));
$resources = $modx->getCollection('modResource', $query);
$ouput = array();
foreach ($resources as $resource)
$output[] = $resource->get('id');
return implode (',', $output);

Specify a page for pagination - Laravel 4

I'm trying to "remember" the page the user was on as he browses through records so that when he returns to the list, he is returned to the page where he left off.
How do I change the "current page" value for paginator?
I've tried Input::set('page', $x); but there's no such function.
$_GET['page'] = $x; doesn't work too.
This the code:
$list = Publication::orderBy($this->data['sort_by'], $this->data['order_by']);
foreach ($this->data['filter_data'] AS $field => $value) {
$list->where($field, 'LIKE', "%$value%");
}
$this->data['list'] = $list->paginate(15);
I looked at the API --- turns out this is much easier now in 2014.
All you have to do is set
Paginator::setCurrentPage(2);
any time before you call ->paginate(), I believe, and it should override the page set (or not set) by ?page=.
You can adjust the page of the pagination environment through the DB connection.
DB::getPaginator()->setCurrentPage(2);
Not entirely sure but you might be able to go through your model with something like this.
Publication::getConnection()->setCurrentPage(2);
If the above isn't working (as it seems from your comment), then do it with an instance of Publication.
$publication = new Publication;
$publication->getConnection()->setCurrentPage(2);
$list = $publication->orderBy(...);
Try
$pager->setCurrentPage(2);

Searching phpbb's 'topic_title' via MYSQL php, but exact match doesn't work

$sql = sprintf( "SELECT topic_title
FROM `phpbb_topics`
WHERE `topic_title` LIKE '%%%s%%' LIMIT 20"
, mysql_real_escape_string('match this title')
);
Which I run this query in phpMyAdmin the results are: (correct)
match this title
match this title 002
But when I run that same MYSQL query in PHP I get: (incorrect)
match this title 002
I have also tried MATCH AGAINST with the same result with both php and phpMyAdmin:
$sql = "SELECT topic_title
FROM phpbb_topics
WHERE MATCH (topic_title)
AGAINST('match this title' IN BOOLEAN MODE)";
The whole block of code im using to search with:
mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("phpbb") or die(mysql_error());
$query = "match this title";
$query = "SELECT topic_title
FROM phpbb_topics
WHERE MATCH (topic_title)
AGAINST('$query' IN BOOLEAN MODE)";
// Doesn't work (these 2 both give the same result "match this title 002" and no the "match this title")
// $query = "SELECT * FROM `phpbb_topics`
// WHERE `topic_title`
// LIKE '%$query%'
// LIMIT 0, 30 "; // Doesn't work
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$topic_title = $row['topic_title'];
echo "$topic_title";
}
Any idea as to what i'm doing wrong?
I'v been searching all over the place and have found next to no help :(
The problem is that after you execute your query you fetch the first row, do nothing with it, enter the loop by fetching the second row and start printing results..
If you remove the first $row = mysql_fetch_array($result), (directly after $result = mysql_query($query) or die(mysql_error());) you should be fine.
Another comment; If you echo a variable you don't have to put any qoutes around it. And in the way you're doing it now, you won't get a newline between the results so you might want to change that line to echo $topic_title . "<br>";

Resources