Laravel - Paginate and get()(Laravel - 分页和 get())
问题描述
使用下面的代码,我想要的是对我创建的查询进行分页.但是,当我尝试在 get 之后添加 paginate 时,它会引发错误.我想保持 get 因为我想限制在 $fields 上设置的列.对这件事进行分页应该是什么更好的主意?或者什么是获取和限制列的好替代品?
With the code below, what I wanted was paginate the query I created. But, when I try to add paginate after get, it throws an error. I wanted to remain get since I want to limit to columns that was set on $fields. What would should be the better idea to paginate this thing? or what's a good substitute for get and limit the columns?
我尝试了什么:
->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);
}
}
推荐答案
如果你看一下 方法签名 你会看到 paginate 接收第二个参数 $columns.所以你的解决方案是使用
If you look at the method signature you will see that paginate receives a second argument, $columns. So your solution would be to use
->paginate($this->limit, $this->fields);
此外,您可以通过稍微改变一些东西来清理您的控制器:
Furthermore, you can clean up your controller by changing things slightly:
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);
}
这篇关于Laravel - 分页和 get()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel - 分页和 get()
基础教程推荐
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01