I have a doubt. I'm using rails 3. And i want to filter my model. Supose, this
class Company
attr_accesible :name, :description
end
In a sql server stored procedure i'd do something like this
select * from Company where (#company_name is null or name like #company_name) and (#company_description is null or description like #company_description) and (#ids is null or id in #ids)
The code above is an example. Is for filter propouses. Which is the proper way to build a query like that?
Thanks in advance
Hope be clear.
Ok, as I understood you have in your view form for #company with name\description\ids fields.
Then in your controller you can do the search like that:
#company = Company.find(:all, conditions:["name LIKE(?) OR description LIKE(?) OR id IN(?)", params[:company][:name], params[:company][:description], params[:company][:ids]])
Related
I have a problem with Laravel 7 Eloquent. I have 2 tables joined by many to many relation. Table user is connected to PaymentModule by pivot table PaymentModuleUser. I need to use where on pivot table on statement is_active = 1. When i use toSQL() in my model SQL returns good results but when i check my Eloquent Query in Controller, data that i revicive ignore my wherePivot method (return all data from table ignoring is_active = 1 field subscribers = null and get me this user.. I must do it if my pivotWhere = null dont show this user). Could you point me where i get wrong with my code?
My UserTable model:
public function subscriber(){
return $this->belongsToMany(PaymentsModule::class, 'payment_module_user', 'user_id')->withPivot('is_active');
}
MyController:
$users = User::with(['subscriber'=>function($query)
{
$query->wherePivot('is_active','=', 1);
}])->get();
print_r($users);
Try with
$users = User::with('subscriber' => function($query) {
$query->where('payment_module_user.is_active', 1);
})->get();
print_r($users);
The pivot table is already joined by eloquent, so just start using it
Found it here.
In your controller, try using this
$query->wherePivot('is_active', 1);
Instead of,
$query->wherePivot('is_active','=', 1);
No, this is just an example not a dating app for pets. My app is different and more complex.
I have a rails app. I have 2 tables House and Pet. A House has many Pet. My Pet table has a JSONB column called pet_description that contains a key value pairs of pet type and gender like so:
{
"dog"=>"male",
"cat"=>"female",
"parrot"=>"male"
}
And the migration file for this is:
class AddPetDescriptionToPets < ActiveRecord::Migration
def change
add_column :pets, :pet_description, :jsonb, default: {}
add_index :pets, :pet_description, using: :gin
end
end
In my House model, I have a query that executes a SQL query. It works if I do this query to find all houses that have pets.
self.where("EXISTS ( SELECT null FROM pets WHERE pets.house_id = houses.id)")
However if I want to query all houses that have a particular pet type and gender then I can't seem to get this query working. I am new to JSONB, what am I doing wrong in the query below?, please help!!!!
self.where("EXISTS ( SELECT null FROM pets WHERE pets.house_id = houses.id AND pets.pet_description #> '{'dog' : 'male'}'::jsonb)")
thanks!
Greg
You may try to use different quotes symbols:
self.where("EXISTS (
SELECT null
FROM pets
WHERE pets.house_id = houses.id
AND pets.pet_description #> '{\"dog\" : \"male\"}'::jsonb)")
Or let Rails take care about params formatting:
self.where("EXISTS (
SELECT null
FROM pets
WHERE pets.house_id = houses.id
AND pets.pet_description #> ?)", {dog: 'male'}.to_json)
what i'm trying to do it's simple search by three columns: firstname, lastname and email
in my case i need that two first colums (firstname and lastname) will be searchable by like operator and the last one (email) by equal operator
but im getting error that does not explain what should i do:
in plain sql it should be something like this:
Select *
From Member
Where FirstName like '%value%' Or LastName like '%value%' Or Email='value'
but what im doing wrong?
You can try with
.Where(Restrictions.Disjunction()
.Add(Restrictions.On(x => x.FirstName).IsLike(keyWord))
.Add(Restrictions.On(x => x.LastName).IsLike(keyWord))
.Add(Restrictions.On(x => x.FirstName).IsLike(keyWord))
.Add(Restrictions.Eq(x.Email,keyWord))
)
I hope it's helpful
Hello I have a table with articles and the articles have a column category. The categories are filled like 1,4,6,8
How can i check if there is a product which has in it for example category 5
I tried something like
select * from article where category in(5);
But that doesn't work. If I use like than i will have a problem with for example 1 and 10. So how can I do this in one mysql query?
Storing CSV in a column you need to query is a bad idea - you should use a separate table.
IN is not for CSVs - it's for listing values for a single column
Those arguments aside, you can use FIND_IN_SET()
For example:
SELECT * FROM article WHERE FIND_IN_SET('5', category) != 0;
You could do it with select * from article where category='5' or category like '5,%' or category like '%,5' or category like '%,5,%'
But you really don't want to do that.
Instead, what you're after is
create table article (
id INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY,
headline VARCHAR(50) NOT NULL,
body VARCHAR(50) NOT NULL
);
create table articlecategory (
article_id INTEGER NOT NULL,
category_id INTEGER NOT NULL,
PRIMARY KEY (article_id, category_id)
);
And then
SELECT
article.*
FROM
article,articlecategory
WHERE
articlecategory.article_id=article.id AND
articlecategory.category_id=5;
try this:
select *
from article
where category like '%,5,%' or category like '5,%' or category like '%,5'
well, that is not the best solution database wise, to have a column with comma separated values. Instead you could have a separate table with two columns, one for the category and one with a article id.
Then you could do:
select * from article, category_articles where category_article.category_id = category.id and category_article.category = 5
Take a look at this for more on database normalization, which this is kinda related to
But if that is not an option you could try using a delimiter and store the data like this: C1C10C, then you could use:
select * from article where category like '%C1C%'
which would not mach 10, but will match the 1.
I can't really think of the best way to phrase this question, so I'll just give an example. Suppose I have a table that is created like this:
CREATE VIEW People
AS
SELECT
id, --int
name, --varchar(20)
birthdate --datetime
FROM SomeTable
If I wanted to change this from a view to a physical table, is there any way to create a table with the same layout?
In other words, I want to take that view and create a table like this:
CREATE TABLE People(
id int,
name varchar(20),
birtdate datetime
)
...but without having to manually write that query out.
This is of course a contrived example. The view has a lot of fields with a lot of different data types, so it would be difficult to do by hand.
How about
SELECT * INTO MyNewTable FROM MyView
AND if you don't want the content, just the structure
SELECT * INTO MyNewTable FROM MyView WHERE 1 = 2
SELECT *
INTO People_Table
FROM People_View
Select * INTO PeopleTable FROM People