我有一个简单的问题,因为我不知道应该将哪条线添加到laravel分页中。 (-> paginate(5)。
public function index(Request $request)
{
$codeSearch = $request->get('code');
$descriptionSearch = $request->get('description');
//$tmp = Category::all()->toArray();
$tmp = Category::where('code','like','%' .$codeSearch. '%')->where('description','like','%' .$codeSearch. '%')->get()->toArray();
$category = array();
foreach ($tmp as $key => $row) {
$policy = Category::find($row['parent_id']);
$tmpResult = new Category();
$tmpResult->id = $row['id'];
$tmpResult->code = $row['code'];
$tmpResult->description = $row['description'];
$tmpResult->parent_id = $policy['description'];
$tmpResult->status = $row['status'];
array_push($category, $tmpResult);
}
return view('category.index', compact('category'));
}
答案 0 :(得分:1)
无法在集合上调用分页,因此您必须在查询上运行它,只需将->get()
替换为->paginate(5)
即可
$tmp = Category::where('code','like','%' .$codeSearch. '%')
->where('description','like','%' .$codeSearch. '%')
->paginate(5)
->toArray();
答案 1 :(得分:0)
以下->get(), ->first(), all()
从数据库中获取结果,-> paginate(5)也是如此,因此,我建议您将->get()
替换为paginate(5)
,这样就可以摆脱toArray()
,因为结果将是一个集合,您可以使用该集合使用foreach()
或按索引获取值。
答案 2 :(得分:0)
当您需要一个条件数组时,只需将最终数组转换为集合对象并使用分页概念即可。
$items = [
'item1',
'item2',
'item3',
'item4',
'item5',
'item6',
'item7',
'item8',
'item9',
'item10'
];
// Get current page form url e.x. &page=1
$currentPage = LengthAwarePaginator::resolveCurrentPage();
// Create a new Laravel collection from the array data
$itemCollection = collect($items);
// Define how many items we want to be visible in each page
$perPage = 1;
// Slice the collection to get the items to display in current page
$currentPageItems = $itemCollection->slice(($currentPage * $perPage) - $perPage, $perPage)->all();
// Create our paginator and pass it to the view
$paginatedItems= new LengthAwarePaginator($currentPageItems , count($itemCollection), $perPage);
// set url path for generted links
$paginatedItems->setPath($request->url());
return view('items_view', ['items' => $paginatedItems]);
答案 3 :(得分:0)
尝试
$tmp = Category::where('code','like','%' .$codeSearch. '%')->where('description','like','%' .$codeSearch. '%')->paginate(5);
可见
@foreach($tmp as $tm)
//whatever operation you like to do
@endforeach
{{$tmp->links()}}
答案 4 :(得分:0)
为Category
的父母建立关系可能会更容易。然后,您可以在检索类别时加载父项。
class Category extends Model
{
...
public function parent()
{
return $this->belongsTo(self::class);
}
}
我觉得您的搜索可能正在尝试进行OR WHERE
,在code
字段中搜索该值或description
:
$categories = Category::with('parent')
->where('code', 'like', '%' .$codeSearch. '%')
->orWhere('description', 'like', '%' .$codeSearch. '%')
->paginate(5);
然后在您的视图中,如果您想要父类别的描述,则可以通过以下关系获取它:
@foreach ($categories as $category)
parent description: {{ $category->parent->description }}
@endforeach