Select in select in laravel - laravel

I recently started learning Laravel and cannot solve my problem with queries.
SELECT * FROM films WHERE id IN (SELECT film_id FROMfavorites WHERE user_id = 2)
This is the correct code, but how to make it for Laravel
I tried to look in documentation, but it's all not that. Maybe someone knows how to solve this problem?

You can use Eloquent model with whereIn() just like below
Films::whereIn('id',Favorites::where('user_id', 2)->pluck('film_id'))->get();
and also if you use Eloquent model with relation, then it'll be more simple as below
$user->favorites()->films

To build it as a query you can use whereIn
\DB::table('films')->whereIn('id', function($query) {
$query->select('id')->from('favorites')->where('user_id',2);
})->toSql();
this will generate
select * from `films` where `id` in (select `id` from `favorites` where `user_id` = ?)

Related

Crudbooster laravel - How to make different column relationship?

I have two table 1. table_a 2. table_b
And all table have company_id. I want to make relationship among this two table using same company id . Like
select * from table_a left join table_b on table_a.company_id = table_b.company_id;
Please help me out if its really possible. Thank you in advance.
You can use this:
$data = DB::table('table_a')->leftJoin('table_b', 'table_a.company_id', '=', 'table_b.company_id')->get();
Or raw:
$users = DB::table('table_a')
->select(DB::raw('query here'))
->get();
More on:
https://laravel.com/docs/5.7/queries

Which of the following is most efficient one and why?

Following is the query which retrives all the order rows from the orders table
$orders = auth()->user()->orders;
or
$orders = Order::where('user_id',auth()->id())->get();
or
$orders = \DB::table('orders')->where('user_id',Auth::id())->get();
If orders table 100 000 rows then which of the above method is ideal to use?
Actually in Laravel you can use toSql method to compare the queries and see which one is the most optimized query like this:
$sql=auth()->user()->orders()->toSql();
But in the example above we see generally all of them are the same:
//First
"select * from `orders` where `orders`.`user_id` = ? and `orders`.`user_id` is not null"
//Second
"select * from `orders` where `user_id` = ?"
//Third
"select * from `orders` where `user_id` = ?"
As you see the second one and the third one are totally the same but the first one has an extra and statement and it's more reliable so I think the execution times are not different and you'd better to use the first one.
compare to laravel eloquent DB:: class is faster way to retrieve data from database but in our case we manage a application in structure way and its depend on your coding standard and module management.
i suggest to use :
$sql=auth()->user()->orders()->toSql();

Laravel - Get the last entry of each UID type

I have a table that has 100's of entries for over 1000 different products, each identified by a unique UID.
ID UID MANY COLUMNS CREATED AT
1 dqwdwnboofrzrqww1 ... 2018-02-11 23:00:43
2 dqwdwnboofrzrqww1 ... 2018-02-12 01:15:30
3 dqwdwnbsha5drutj5 ... 2018-02-11 23:00:44
4 dqwdwnbsha5drutj5 ... 2018-02-12 01:15:31
5 dqwdwnbvhfg601jk1 ... 2018-02-11 23:00:45
6 dqwdwnbvhfg601jk1 ... 2018-02-12 01:15:33
...
I want to be able to get the last entry for each UID.
ID UID MANY COLUMNS CREATED AT
2 dqwdwnboofrzrqww1 ... 2018-02-12 01:15:30
4 dqwdwnbsha5drutj5 ... 2018-02-12 01:15:317
6 dqwdwnbvhfg601jk1 ... 2018-02-12 01:15:33
Is this possible in one DB call?
I have tried using DB as well as Eloquent but so far I either get zero results or the entire contents of the Table.
Andy
This is easy enough to handle in MySQL:
SELECT t1.*
FROM yourTable t1
INNER JOIN
(
SELECT UID, MAX(created_at) AS max_created_at
FROM yourTable
GROUP BY UID
) t2
ON t1.UID = t2.UID AND
t1.created_at = t2.max_created_at;
Translating this over to Eloquent would be some work, but hopefully this gives you a good starting point.
Edit: You may want to use a LEFT JOIN if you expect that created_at could ever be NULL and that a given UID might only have null created values.
You can use a self join to pick latest row for each UID
select t.*
from yourTable t
left join yourTable t1 on t.uid = t1.uid
and t.created_at < t1.created_at
where t1.uid is null
Using laravel's query builder it would be similar to
DB::table('yourTable as t')
->select('t.*')
->leftJoin('yourTable as t1', function ($join) {
$join->on('t.uid','=','t1.uid')
->where('t.created_at', '<', 't1.created_at');
})
->whereNull('t1.uid')
->get();
Laravel Eloquent select all rows with max created_at
Laravel Eloquent group by most recent record
SELECT p1.* FROM product p1, product p2 where p1.CREATED_AT> p2.CREATED_AT group by p2.UID
You can achieve this with eloquent using orderBy() and groupBy():
$data = TblModel::orderBy('id','DESC')->groupBy('uid')->get();
SOLVED
Thanks to Tim and M Khalid for their replies. It took me down the right road but I hit a snag, hence why I am posting this solution.
This worked:
$allRowsNeeded = DB::table("table as s")
->select('s.*')
->leftJoin("table as s1", function ($join) {
$join->on('s.uid', '=', 's1.uid');
$join->on('s.created_at', '<', 's1.created_at');
})
->whereNull('s1.uid')
->get();
However I got an Access Violation so I had to go in to config/database.php and set
'strict' => false,
inside the 'mysql' config, which removes ONLY_FULL_GROUP_BY from the SQL_MODE.
Thanks again.
You have to use ORDER BY, and LIMITSQL parameters, which will lead you to an easy SQL request :
for exemple, in SQL you should have something like this :
SELECT *
FROM table_name
ORDER BY `created_at` desc
LIMIT 1
This will returns everything in the table. The results will be ordering by the column "created_at" descending. So the first result will be what you're looking for. Then the "LIMIT" tells to return only the first result, so you won't have all your database.
If you wanna make it with eloquent, here is the code doing the same thing :
$model = new Model;
$model->select('*')->orderBy('created_at')->first();

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.

Codeigniter select multiple rows?

How do I select multiple rows from SQL?
ie. $results->row(1,2,3,4,5,10)
Are you using ActiveRecord? If so, you can use the where_in() method when making your query. It's not something you do after the query is finished, as you seem to be doing in your example.
$this->db->where_in('id', array(1,2,3,4,5,10));
$query = $this->db->get('myTable');
// This produces the query SELECT * FROM `myTable` WHERE `id` IN (1,2,3,4,5,10)
See the this CodeIgniter docs section for more info on SELECT statement support.

Resources