phpmysqllaravel

Delete distinct data


I have Laravel project and I have this model

User_attendance

User

and I have this relation inside User

public function getAttendance()
{
    return $this->hasMany('App\User_attendance','user_attendance_user_id','id');
}

now there is duplication data in User_attendance like this

9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-27 17:45:48
9238<><> 2018-11-28 17:35:00
9238<><> 2018-11-29 17:44:34
9238<><> 2018-12-08 17:18:12
9238<><> 2018-12-08 17:18:12

Now 9238<><> 2018-11-27 17:45:48 has 12 records.

How can I run query inside Laravel or MySQL to delete 11 records and leave only 1. I did this:

$users = User::limit(30)->get();
foreach($users as $u)
{
    foreach($u->getAttendance as $attendance)
    {
        echo $attendance->user_attendance_user_id . "<><> ".$attendance->created_at ."<br />";
    }
}

I want to delete the duplicate data and leave only one record.


Solution

  • Use the DISTINCT or GROUP BY keyword

    Example:

    SELECT DISTINCT(column),column1,column2,... FROM table_name;

    SELECT * From User_attendance GROUP BY user_attendance_user_id,created_at;