laravel复杂的数据库查询(事例)

/**
 * Created by PhpStorm.
 * User: [email protected]
 * Date: 2017/9/3
 * Time: 下午4:12
 */

namespace App\Containers\ConsultingUser\Data\Criterias;


use App\Containers\ConsultingUser\Models\ConsultingUser;
use App\Containers\User\Models\User;
use App\Ship\Parents\Criterias\Criteria;
use function foo\func;
use Prettus\Repository\Contracts\RepositoryInterface;

class ConditionSearchCriteria extends Criteria
{
    private $search;
    private $status;
    private $role;
    private $department;
    private $startTime;
    private $endTime;

    public function __construct($search, $status = null, $role = null, $department = null, $startTime = null, $endTime = null)
    {
        $this->search = $search;
        $this->status = $status;
        $this->role = $role;
        $this->department = $department;
        $this->startTime = $startTime;
        $this->endTime = $endTime;
    }

    /**
     * @param ConsultingUser $model
     * @param RepositoryInterface $repository
     * @return mixed
     */
    public function apply($model, RepositoryInterface $repository)
    {
        // TODO: Implement apply() method.
        $search = $this->search;
        $status = $this->status;
        $role = $this->role;
        $department = $this->department;
        $startTime = $this->startTime;
        $endTime = $this->endTime;
        $model->join('users', function($join) use ($search, $status, $startTime, $endTime){
            $join->on('users.user_type_id', '=', 'consulting_user.id')
                ->where('users.user_type', '=', User::CONSULTING_COMPANY)
                ->where('users.name', 'like', "%{$search}%");
            if ($status !== null) {
                $status = (integer) $status;
                if ($status === 0) {
                    $join->where('users.deleted_at', '!=', null);
                }
                if ($status === 1) {
                    $join->where('users.deleted_at', '=', null);
                }
            }
            if ($startTime) {
                $join->where('users.created_at', '>=', $startTime);
            }
            if ($endTime) {
                $join->where('users.created_at', '<=', $endTime);
            }
        });
        if ($role) {
            $model->join('user_has_roles', function($join) use ($role){
                $join->on('users.id','=','user_has_roles.user_id')
                    ->where('user_has_roles.role_id','=',$role);
            });
        }
        if ($department) {
            $model->join('user_has_department', function($join) use ($department){
                $join->on('users.id','=','user_has_department.user_id')
                    ->where('user_has_department.department_id','=',$department);
            });
        }
        return $model->select('consulting_user.*');
    }

}

你可能感兴趣的:(laravel复杂的数据库查询(事例))