how to get latest record from the database having same id in laravel? - laravel

I am trying to to get latest record having the same id. For example
I have table
ID | Created_at
1 |2016-04-26
1 |2016-04-20
1 |2016-04-18
2 |2016-04-27
2 |2016-04-19
I want to get result like this
ID | Created_at
1 |2016-04-26
2 |2016-04-27
How do I do this in Laravel? I was only able to order the record by descending order. Don't know how to pick the latest record of each ID. Thank you.

Try using Collections service from laravel , and use last() method. Example:
$data = ModelName::all();
$last_data_object = collect($data)->last();
//try to see the object using var_dump()
var_dump($last_data_object);
I get it from https://laravel.com/docs/5.2/collections#method-last

You can try with whereRaw to getting last records in groupBy laravel
$data = Table::whereRaw('Created_at IN (select MAX(Created_at) FROM table GROUP BY ID)')->get();

Try it this way, it will give you the max grouped ID which will be the latest:
SELECT MAX(ID), Created_at
FROM table
GROUP BY ID, Created_at

Thank you everyone for help. I was able to solve this by
DB::raw("SELECT ID,created_at FROM <table name> a WHERE created_at=(SELECT max(created_at) FROM <table name> b WHERE a.ID=b.ID)

DB::raw('SELECT * FROM `test` WHERE 1 GROUP BY `ID` ORDER BY `Created_at` ASC');
Try this

Include the directive Db
$id = DB::table('your_table')->orderBy('id', 'desc')->value('id');
If you have user_id.
$id = DB::table('your_table')->where('user_id', $user_id)->orderBy('id', 'desc')->value('id');

Related

How to Syntax OrderBy whit value in eloquent

I need to add a by order with value in eloquent, how can I do it?
example
Order By
c.id = 23 DESC
enter image description here
Is this a joined table if yes show model and controller?
if it not joined table then try this:
->orderBy('c.id','DESC'), or ->orderByCId('DESC') or ->orderByDesc('c.id')

Select in select in 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` = ?)

How to get records from a table if it does not exist in another related table laravel query builder

I have two tables
tb_teachers
-----------
id
name
school_id
tb_class_to_teachers
--------------------
id
teacher_id
class_id
assigned_status
school_id
How to get records from tb_teachers if it(teacher_id and school_id) does not exist in another related table tb_class_to_teachers using laravel query builder
I assume you set up your relationship correctly, then u may use doesntHave
$teachers = App\Teachers::doesntHave('class')->get();
try this
$classToTeachers = DB::table('tb_class_to_teachers')->get();
if($classToTeachers->teacher_id == null && $classToTeachers->school_id == null)
{
$teacher = DB::table('tb_teachers')->get();
}

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();

get both by ID and Name in laravel?

In MySQL Database Table there are 2 columns
Order TypeID
Order Type
In Order to find a record with ID, I am using below code.
$OrderType = \App\Models\OrderType_Model::find($request->input('OrderTypeID'));
Is there any way to get both by ID and Name ?
You can use a orWhere clause
$orderType = OrderType_Model
->where('OrderTypeId',$request->input('OrderTypeId))
->orWhere('OrderType', $request->input('OrderType))
->first();
$OrderType = \App\Models\OrderType_Model
::where("OrderTypeID", "!=", $request->input('OrderTypeID'))
->where("OrderType", '=', $request->input('OrderType'))->first();

Resources