RedBean php count query with where - redbean

I need a count query in redbean php with where condision
I used
R::count("company","country like 'United States'");
where country name is the where condision
plz suggest some thing

Redbean expects an array on 3rd parameter, so you should use:
R::count("company", "country like ?", ["United States"]);
note that every ? should match one element in array, but if you have more conditions for the same value, you can also use :param once instead, for ex:
R::count("company", "country like :name OR city like :name", [":name" => "United States"]);

R::count("company","country like 'United States'");
this works fine.........
but this doesn't
R::count("company","country like '".$country."'");

Related

postgresql and RoR - how quering a json type field where value is in an array

Say I have a User class with a json type address field that has keys for city and country like this: adress: {city: 'NY', country: 'USA'} and I want to get all the users that live in an array of country names like: country_names = ['Iran', 'Iraq', 'Yemen'].
How do can I do it in Ruby on Rails?
I've tried:
User.where("address->>'country' IN ?", country_names)
but I get a syntax error. what is the correct way?
The list of values of the IN clause should be enclosed by parentheses:
User.where("address->>'country' IN (?)", country_names)

Ruby on Rails search with array of values to find in multiple fields (datatables)

I implemented datatables like proposed on the http://railscasts.com/episodes/340-datatables and it works just fine. Unfortunately it doesnt concern the point of searching with spaces in the input field. If I implement it with the search function processing it with javascript it works just fine.
So what I want to do is search on the database on many fields where the parameters of the sql are splitted by space (dynamic size of parameters)
eg. "name1 street city" -> this means returned objects must contain all three "name1", "street", "city" in one of the objects fields.
Here's an example:
Person :name, :address, :city, :country
Person("Peter Mayer", "Some Street 111", "New York", "United States")
if a user searches with "Peter York" it should find the object
if a user searches with "Peter Los Angeles" it should not find anything
if a user searches with "111 Mayer States York" it should find the object
okey, i could write many different sql's respecting the amount of params but that istn't so nice
Is there an easy way to solve that?
Filtering after searching with just the first param isn't an option since pagination wouldnt work anymore
You could do the following:
Join all the attributes that must be found in one string
search_attributes = [person.name1, person.address, person.city, person.country].join(' ')
for your example search_attributes would be equal to "Peter Mayer Some Street 111 New York United States"
Then you iterate over every string in the query and make sure it is found in search_attributes using .include?, and return a record only if all strings in the sent query are found in search_attributes
I did it like this now:
searchData = params[:sSearch].split(" ")
searchString = "1 = 1"
searchParams = {}
i = 0
searchData.each do |searchParam|
searchString += " AND (persons.name like :search"+i.to_s+" or persons.address like
:search"+i.to_s+" or persons.city like :search"+i.to_s+" or persons.country like
:search"+i.to_s+"+")"
searchParams["search#{i}".to_sym] = "%"+searchParam+"%"
i += 1
end
Person.where(searchString, searchParams)

Rails activerecord LIKE AND clause error

Here is an activerecord query i'm trying to use in rails
q = "Manchester"
b = "John Smith"
Model.find(:all, :conditions => ["city ? AND name like ?", q, b])
but i get this error in rails console
ActiveRecord::StatementInvalid: SQLite3::SQLException: near "'Manchester'": syntax error: SELECT "model".* FROM "model" WHERE (city 'Manchester' AND name like 'John Smith')
Please help!
You missed LIKE for city.
Model.where('city LIKE ? AND name LIKE ?', "%#{q}%", "%#{b}%");
You can also use this syntax which is a lot more readable than trying to figure out which ? goes with which variable. I mean if you have 1 or 2 it's fine, but once you have more it gets pretty ugly.
Model.where("city LIKE :city AND name LIKE :name", { city: "%#{q}%", name: "%#{b}%" })
The placeholders and hash key can be anything you like as long as they match (don't use :city and then hamster: in the hash key for example).
The nice thing about this is that you can also use one variable for multiple searches:
where("user LIKE :term OR email LIKE :term OR friends LIKE :term", { term: "%#{params[:term]}%"})
Try this:
Model.find(:all, :conditions => ["city = ? AND name like ?", q, b])

Rails: Multiple or conditions in ActiveRecord

I have two tables: Lawyer and Phone. Phone is separated into area code and number. A lawyer has many phones. I want to produce a query that searches for lawyers who have a phone matching a phone from a list of phones.
If I had only one phone I could search it like this:
Lawyer.join(:phones).where(:area_code => area_code, :number => number)
The problem is that I have a list with more than one area code. So I really want to do something like this:
lawyers = []
phones.each { |phone| lawyers += Lawyer.join(:phones).where(:area_code => phone[:area_code], :number => phone[:number]) }
However, I don't want to make many queries. Can't it be done in a single query statement?
Edit: This is how I would do a similar thing using SQL alone (assuming the list of numbers was [{:area_code=>'555', :number=>'1234564'}, {:area_code=>'533', :number=>'12345678'}])
select * from phones where (area_code, number) in (('555', '1234564'), ('533', '12345678'))
If someone can get that translated into ActiveRecord, that'd be great.
If you pass an array of area_codes, AR will build an IN condition. So you could use your original search and use arrays instead:
where area_codes is an array of area_codes and numbers an array of numbers:
Lawyer.join(:phones).where(:area_code => area_codes, :number => numbers)
or:
Lawyer.join(:phones).where("phones.area_code IN (?) AND phones.number IN (?)", area_codes, numbers)
Should yield:
SELECT * from lawyers JOIN phones ON phones.lawyer_id = lawyers.id WHERE phones.area_code IN (...) AND phones.number IN (...)
Lawyer.join(:phones).where(
"(phones.area_code, phones.number) IN ( ('555', '5555555'), ('444', '12345678') )"
)

How find table column with different values -rails

The Case:
table - movie:
columns:
rating:
title:
Query 1- get all
Movie.all(:order => "title ASC");
Query 2- get with rating="G" || rating="K" ---Not working
ratingsArr=["G","K"]; also can be = [] =>real code params[:ratings] ..
Movie.all(:order => "title ASC", ratingsArr);
How should I build Query 2? ratingsArr may or may not be empty. User set params, according them ratingsArr has the value.
I believe you need to use Movie.where(:rating => ratingsArr).order("title ASC")
Being new, you should read the Rails Guides and perhaps the API documentation for ActiveRecord
Try this:
Movie.where( params[:ratings].present? ? {:rating => params[:ratings]} : {} ).
order("title ASC");
You should be able to use the SQL IN operator by doing: Movie.where(:rating => ratings_array).order("title ASC")
Note that I changed ratingsArr to ratings_array. This is code convention for Ruby. CamelDot is only used for Class names. In variables words are seperated by _

Resources