How to Add OR Condition in Laravel Sphinx query? - php

I am using the fobia/laravel-sphinx package and want to add a condition like city != 0 or state != 0 but the or condition is not working and gives tjis error:
"Syntax error or access violation: 1064 sphinxql: syntax error,
unexpected OR, expecting $end near 'or "
$query->where('state_id', '!=', 0)->orWhere('city_id', '!=', 0);
It uses \Fobia\Database\SphinxConnection\Eloquent\Model

If you have a version of sphinx/manticore server that is not supporting OR conditions, have to 'fake' using a fake attribute/expression.
Need to add a column. Want SphinxQL somewhat like
SELECT *, (state_id!=0)+(city_id!=0) as filter FROM index WHERE filter > 0
... ie will only inlcude rows, where the sum of state_id and city_id is above zero. Ie either one of them is not zero.
Alas reading the laravel-sphinx source, can't figure out how to add to the columns list. Seems needs needs adding to $query->columns. So dont know if something like
$query->columns[] = "(state_id!=0)+(city_id!=0) AS filter";
$query->where('filter', '>', 0);
or maybe
$query->select(['*',"(state_id!=0)+(city_id!=0) AS filter"])->where('filter', '>', 0);
seems the there is a 'select' method in the base query builder
https://laravel.com/api/5.5/Illuminate/Database/Query/Builder.html

you cant use OR condition in Sphinx
you can handle it with whereNotIn and whereIn

These are the top rated real world PHP examples of yii\sphinx\Query::orWhere extracted from open source projects. You can rate examples to help us improve the quality of examples.
Please Visit and see example

Related

Doctrine DQL - Logic check in select

I am trying to use a LIKE comparison in a doctrine DQL in a MySQL database.
It works directly in SQL in the database and looks like this:
SELECT *, (name LIKE '%testO%') as partOfName
from organization
ORDER BY partOfName DESC;
This works just fine.
Now I try to implement this logic in Doctrine. My Querybuilder looks like this:
oQueryBuilder
->from(OrganizationEntity::class, organization)
->select('organization')
->addSelect('(organization.name LIKE %:searchTerm%) AS searchTermIsPartOfName')
->setParameter('searchTerm', $sSearchTerm)
->orderBy('searchTermIsPartOfName', 'DESC')
;
Trying to run it or get the SQL out of it gives me the following error:
[Syntax Error] line 0, col 97: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got 'LIKE'
It is definitely the part about the LIKE. I commented the last three lines out and it works.
How do I translate the above working SQL into Doctrine DQL?
LIKE expressions are covered under Conditional Expressions in DQL's grammar. And unfortunately, it's not possible to use these directly within a SelectExpression.
However you can use them within a CaseExpression, which can be used in a SelectExpression, and replicate the same behaviour:
->addSelect('CASE WHEN (organization.name LIKE :searchTerm) THEN 1 ELSE 0 END AS searchTermIsPartOfName')
->setParameter('searchTerm', "%{$sSearchTerm}%")
(there was also a minor issue about your LIKE expression - I'm pretty sure the % signs need to be part of the parameter value, not the query itself)
you forgot '' after LIKE, replace with string
->addSelect('(organization.name LIKE %:searchTerm%) AS searchTermIsPartOfName')
on
->addSelect('(organization.name LIKE \'%:searchTerm%\') AS searchTermIsPartOfName')

Yii2 db query builder having into where

Sorry on my English. I add new condition to my query like this:
$query->andWhere(['or',
["<", "o.score", $score_operator],
["<", "d.score", $score_delivery],
["<", "SUM(sd.score)/count(DISTINCT sd.id)",$score_dishes]]);
Buth I got error:
General error: 1111 Invalid use of group function
Then I read that I must use having in 3-d row, but I don't know how to put "having" in "where" condition.
For condition/filter related to aggregation function you should use having and not where
$query->having("SUM(sd.score)/count(DISTINCT sd.id) < " .$score_dishes);
where work on table rows having work on selected result rows.
http://www.yiiframework.com/doc-2.0/yii-db-query.html#having()-detail
starting for 2.0.11 you could use also filteHaving in case you having http://www.yiiframework.com/doc-2.0/yii-db-query.html#filterHaving()-detail

%LIKE% retrieves eg. WOMEN DATA when calling MEN

$itemList = DB::table('items')
->orderBy('id', 'desc')
->where('item_status', 2)
->where(function($query) use($queryArr)
{
foreach($queryArr as $uID){
$query->whereRaw("tags LIKE '%$uID%'");
}
})->paginate(21);
I have been facing this issue since a long time. Problem when you do a LIKE search is it grabs the data of WOMEN when it's just eg MEN
Mainly because MEN is inside Women
I also tried the following but failed(This sort of grab a word) men without women data
$query->where('tags', 'LIKE', '%'.$uID.'%');
SELECT 'a word a' REGEXP '[[:<:]]word[[:>:]]';
How do i use that Word boundary query in laravel query builder
Tried this and still failed $query->whereRaw("tags LIKE REGEXP '[[:<:]]Men[[:>:]]'");
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'REGEXP '[[:<:]]Men[[:>:]]')' at line 1 (SQL: select count(*) as aggregate from items where item_status = ? and (tags LIKE REGEXP '[[:<:]]Men[[:>:]]')) (Bindings: array ( 0 => 2, ))
I also understand some asked why not just created a proper way of handling these item's category. Well i think for now using Full Text Search is fine for me at most when it come to scaling i will use elastic search. true?
UPDATE
Apologies for not giving an example of tags
Bag,Shoes,Men,Wedges
Bag,Shoes,Men
Men,Shoes,Bag
If values are separated by commas, try to use following
WHERE `tags` REGEXP "(^|,)men(,|$)"
This will require to have comma or end of string around the word men.
Your REGEXP solution is throwing the syntax error because of the extra LIKE keyword. The correct syntax is simply WHERE column REGEXP 'pattern'.
If you find this hard to remember, try using RLIKE instead, which is a synonym for MySQL's REGEXP. There is less chance you will accidentally write WHERE column LIKE RLIKE ... in your query because it is more obviously redundant.
The pattern itself should work fine. Personally, I dislike using those word boundary classes in MySQL; since you know your tags are comma delimited and space padded, [ ,]Man[ ,] would function just as well. The word boundary class breaks at punctuation other than underscores, so you could run into trouble if you have tags that are hyphenated, for instance.
If you want to use multiple word tags with spaces, either of the previous patterns is buggy. In that case I would try to stick with commas as your delimiter, get rid of the whitespace padding and use anchors instead, as suggested in one of the other answers: (^|,)Man($|,)
In your query you said : Find anything that contains the tag 'MEN' => '%MEN%', that's why it shows: WOMEN AND MEN, so to answer to your question you should use starts with instead of contains, like this :
$query->where('tags', 'LIKE', $uID.'%');

count of items from another table for each row in table

I have a list of user-profiles when I have this query. I want to retrieve nr of followers for each (every) user, but I only get one row result from query (there are a lot of users)
$this->db->select('up.name, up.id, up.image, up.name_id, up.created, COUNT(followers.user_id) as followed_by_count');
$this->db->join('user_profiles up', 'u.id = up.user_id', 'left');
$this->db->join('followers', 'up.user_id = followers.user_id', 'left');
//Something like this? (It doesn't work)
//$this->db->group_by('COUNT(followers.user_id) as followed_by_count');
//When tried this I get:
//"You have an error in your SQL syntax; check the manual that corresponds to your
//MySQL server version for the right syntax to use near 'as followed_by_count"
$this->db->order_by('up.created', 'DESC');
I guess I should use group by in some way? The query works when not using followers-table. It also works when not using group_by but I obviously don't get the count(s) I want then.
Change
$this->db->group_by('COUNT(followers.user_id) as followed_by_count');
To
$this->db->group_by('u.id');
Note : This code given as per your given code and assume that your code is syntactically right.

Magento: Filtering a getCollection is not working

My getCollection code is providing the wrong query string (i think).
I have a table called banner which I can load all records from easy enough. When I try to filter it I'm getting errors.
Here is the code:
$banner = Mage::getModel('banner/banner')->getCollection()->addFieldToFilter('group', array('eq'=>'search_group'));
The page crashes and I get this error:
1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'group = 'search_group')' at line 1";i:1;s
As you can see it seems like the code is messing up the quotes after group.
'group = 'search_group')'
Can anyone advice on how to fix this?
Thanks,
Billy
group is an SQL keyword. If group is also an attribute name you'll need to escape it somehow. Try using backticks (the typically unused key below Esc).
$banner = Mage::getModel('banner/banner')
->getCollection()
->addFieldToFilter('`group`', 'search_group');
You're misinterpreting the error text.
to use near 'group = 'search_group')'
The outer quotes are the error messages way of blocking something off as code. This probably would have been clearer
to use near [group = 'search_group')]
It's always best to look at the select your collection is using (assuming a a non-eav collection here, given your Module Creator style class alias) and try running in directly in your MySQL client (PHPMyAdmin, Command Line app, Query analyzer, Sequel Pro, etc.)
header('Content-Type: text/plain');
echo (string) $widget->getSelect();
echo "\n";
var_dump ( (string) $widget->getSelect());
Mage::Log((string) $widget->getSelect());
exit;
Seeing the entire query in context usually makes spotting an error easier.
One way will be:-
Write the following function in your collection class:-
public function setGroupBy($group)
{
$this->getSelect()->group($group);
return $this;
}
Then you can use it like:-
$banner = Mage::getModel('banner/banner')->getCollection()->setGroupBy('search_group');
Hope this helps.

Categories