从复杂的原始SQL查询创建Eloquent模型

时间:2015-08-16 13:53:51

标签: mysql laravel laravel-5 eloquent laravel-5.1

我正在考虑该方法的正确设计,该方法为用户提供了很久以前最后一次约会的客户列表。

所以我有2个表(简化):

  • 客户端(id,first_name)
  • 约会(id,client_id,datetime)

我想做的是:获取最近一次约会的3位客户名单。

所以我做的是:我选择具有最早约会的用户并返回它们(使用复杂的SQL查询)。然后我从他们创建模型。

这种情况的设计好吗?

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;
    }

}

0 个答案:

没有答案