2013-10-27 5 views
9

С помощью приведенного ниже кода я хотел был разбивать запрос на запрос, который я создал. Но, когда я пытаюсь добавить paginate после получения, он выдает ошибку. Я хотел остаться get, так как хочу ограничить столбцы, которые были установлены в $ fields. Что было бы лучшей идеей для разбивки этой вещи? или что является хорошей заменой для получения и ограничения столбцов?Laravel - Paginate and get()

Что я пробовал:

->get($this->fields)->paginate($this->limit) 

Часть моего контроллера:

class PhonesController extends BaseController { 

    protected $limit = 5; 
    protected $fields = array('Phones.*','manufacturers.name as manufacturer'); 
    /** 
    * Display a listing of the resource. 
    * 
    * @return Response 
    */ 
    public function index() 
    { 



     if (Request::query("str")) { 
      $phones = Phone::where("model", 'LIKE', '%'. Request::query('str') . '%') 
         ->join('manufacturers', 'manufacturers_id', '=', 'manufacturers.id') 
         ->get($this->fields); 

     } else { 
      $phones = Phone::join('manufacturers', 'manufacturers_id', '=', 'manufacturers.id') 
          ->get($this->fields); 
     } 



     return View::make('phones.index')->with('phones', $phones); 
    } 

}

ответ

17

Если вы посмотрите на method signature вы увидите, что постраничной получает второй аргумент, $ столбцов , Таким образом, ваше решение будет использовать

->paginate($this->limit, $this->fields); 

Кроме того, вы можете очистить ваш контроллер, изменяя вещи немного:

public function index() 
{ 

    $query = Phones::join('manufacturers', 'manufacturers_id', '=', 'manufacturers.id'); 

    if (Request::query('str')) { 
     $query->where('model', 'LIKE', '%'. Request::query('str') . '%') 
    } 

    $phones = $query->paginate($this->limit, $this->fields); 

    return view('phones.index')->with('phones', $phones); 
} 
+0

он не работает в Laravel 5.1 –

1
class Servicios extends CI_Controller 
{ 

    public function __construct() 
    { 

     parent::__construct(); 

     header('Content-Type: application/json'); 
     if (!$this->lib_validaciones->validarSesion(FALSE)) 
     { 
      exit(json_encode(array("satisfactorio" => FALSE, "mensaje" => "NO TIENE SESSION ACTIVA"))); 
     } 
     $this->usuarioId = $this->session->userdata("usuarioId"); 
    } 

    public function index() 
    { 
     exit(); 
    } 

    public function getPremios() 
    { 
     $currentPage = $this->input->get("pag"); 

     \Illuminate\Pagination\Paginator::currentPageResolver(function() use ($currentPage) 
     { 
      return $currentPage; 
     }); 

     $this->load->model('Premio'); 

     $premios = Premio::where('activo', "TRUE") 
       ->with(['Categoria' => function($q) 
        { 
         $q->select('id', 'nombre'); 
        }]) 
       ->with(['Imagenes' => function ($query) 
        { 
         $query->where("activo", "TRUE"); 
         $query->select(["imagenes.id", "imagenes.descripcion", 
          new Illuminate\Database\Query\Expression(
            "CONCAT('" . site_url(PATH_IMAGENES_UPLOAD) . "',imagenes.id,'.',imagenes.extension) as path") 
         ]); 
        }]) 
       ->with(['inventario']) 
       ->withCount(['Favoritos', 'Favoritos AS favorito_usuario' => function ($query) 
        { 
         $query->where("usuario_id", $this->usuarioId); 
        }]) 
       ->orderBy("nombre") 
       ->paginate(3); 

     $premios->setPath(site_url(uri_string())); 
     $premios->setPageName("pag"); 

     exit(json_encode(array("satisfactorio" => TRUE, "premios" => $premios->toArray()))); 
    } 

} 
Смежные вопросы