ActiveRecord WHERE NOT EXISTS - activerecord

Is there a way to use EXISTS with ActiveRecord besides find_by_sql?
I'd like a nice way to find all records without an association in a One-to-Many relationship.
SELECT DISTINCT store_type FROM stores
WHERE NOT EXISTS (SELECT * FROM cities_stores
WHERE cities_stores.store_type = stores.store_type)

Store.all(:select => "DISTINCT store_type",
:conditions => "NOT EXISTS (SELECT * FROM cities_stores WHERE cities_stores.store_type = stores.store_type)")
ActiveRecord will execute the same query as what you entered above. The returned Store instances will have a single store_type attribute.

Related

Laravel eloquent distinct select with possibility to call relation?

I want to select distinct results from one table, the structure is following:
id, user_id, category_id, last_answered_question_id
I have relation for last_answered_question_id called: lastAnsweredQuestion()
My query is:
Answer::select('category_id')->where(['user_id' => $userId])->distinct()->get();
This query works as expected but in this case I can't call relation $answer = lastAnsweredQuestion.
Is there any known way to get distinct items and call relation lastAnsweredQuestion() anyway?

How to make case join statement by using activerecord

I have two different table.
(1)dog_breeds
(2)cat_breeds
now in the third table, I have column name pet_cat. Now I want to join with dog_breeds if pet_cat == 1 else join with cat_breeds. How can I do this just by using CodeIgniter active record.

Running "exists" queries in Laravel query builder

I'm using MySQL and have a table of 9 million rows and would like to quickly check if a record (id) exists or not.
Based on some research it seems the fastest way is the following sql:
SELECT EXISTS(SELECT 1 FROM table1 WHERE id = 100)
Source: Best way to test if a row exists in a MySQL table
How can I write this using Laravel's query builder?
Use selectOne method of the Connection class:
$resultObj = DB::selectOne('select exists(select 1 from your_table where id=some_id) as `exists`');
$resultObj->exists; // 0 / 1;
see here http://laravel.com/docs/4.2/queries
Scroll down to Exists Statements, you will get what you need
DB::table('users')
->whereExists(function($query)
{
$query->select(DB::raw(1))
->from('table1')
->whereRaw("id = '100'");
})
->get();
This is an old question that was already answered, but I'll post my opinion - maybe it'll help someone down the road.
As mysql documentation suggests, EXISTS will still execute provided subquery. Using EXISTS is helpful when you need to have it as a part of a bigger query. But if you just want to check from your Laravel app if record exists, Eloquent provides simpler way to do this:
DB::table('table_name')->where('field_name', 'value')->exists();
this will execute query like
select count(*) as aggregate from `table_name` where `field_name` = 'value' limit 1
// this is kinda the same as your subquery for EXISTS
and will evaluate the result and return a true/false depending if record exists.
For me this way is also cleaner then the accepted answer, because it's not using raw queries.
Update
In laravel 5 the same statement will now execute
select exists(select * from `table_name` where `field_name` = 'value')
Which is exactly, what was asked for.

Rails find all Customers that have exactly 1 Order

I have a data model where a Customer has many Orders. I now need to extract all of the customers that have only placed 1 order and I am scratching my head trying to figure out what to do.
Use this
Customer.joins(:orders).group(:id).having("count(orders.id) = 1")
this will create a query like:
SELECT "customers".* FROM "customers" INNER JOIN "orders" ON
"orders"."customer_id" = "customers"."id" GROUP BY id HAVING
count(orders.id) = 1
You would get all of the customers that have placed exactly 1 order.
To avoid ambiguous reference to the ID field, this would be used:
Customer.joins(:orders).group("customers.id").having("count(orders.id) = 1")
which would generate the following SQL:
SELECT "customers".* FROM "customers" INNER JOIN "orders" ON "orders"."customer_id" =
"customers"."id" GROUP BY customers.id HAVING count(orders.id) = 1
Consider Customer and Order are ActiveRecord classes and consider you have a code line
belongs_to :customer in your Order class definition. And also consider that Order table have a foreign_key or index column named customer_id do as below to get this Customer objects.
Customer.joins(:orders).where("count(orders.id) = 1")

How can I use Linq to join between objects and entities?

I have a collection of IDs in memory, and I would like to fetch only rows from a DB matching those IDs.
In SQL, I could either write a query like SELECT * FROM mytable WHERE id IN (1,3,5,10) or do a join between tables.
My problem is that EF can't build a query where I join my EF-data with my local array or list.
(I'm using EF4.1, but I'm guessing the problem/solution would be similar in older versions, as well as with Linq-to-SQL.)
You can use Contains() with your ID collection myIDs to generate the equivalent WHERE id IN .. query:
var results = context.mytable.Where(x => myIds.Contains(x.Id));

Resources