I am thinking about the right design of the method which gives user a list of clients who's last appointment was long time ago.
So I have 2 table (simplified):
- Clients (id, first_name)
- Appointments (id, client_id, datetime)
What I am trying to do: get the list of 3 clients who's last appointment was long time ago.
So what I do: I select users with the oldest appointments and return them (with complex SQL query). Then I create models from them.
Is it good design for this case?
use Illuminate\Database\Eloquent\Collection;
class ClientRepository {
/**
* Get clients with no appointments in the near history (sort by the date of last appointment ASC)
*
* @todo Make a better way to find falling clients (more Laravelish maybe?)
* @param $count How many clients should method return
* @return Illuminate\Database\Eloquent\Collection
*/
static public function getLost($count=3) {
//this SQL looks too long but works as charm
//solution based on http://stackoverflow.com/questions/1066453/mysql-group-by-and-order-by
$sql = "
SELECT * FROM (
SELECT clients.*, clients.id AS cli_id , appointments.datetime AS last_appointment_datetime
FROM clients
INNER JOIN appointments ON clients.id=appointments.client_id
ORDER BY appointments.datetime ASC
) AS tmp_table
GROUP BY cli_id
ORDER BY last_appointment_datetime ASC
LIMIT ?
";
$users = \DB::select($sql,[$count]);
foreach($users as $key=>$user) {
$user_array = (array)$user;
$users[$key] = new Client();
$users[$key]->forceFill($user_array);
}
$collection = new Collection($users);
return $collection;
}
}