Laravel获取并分页相同的数据

时间:2017-12-22 04:56:03

标签: php laravel pagination eloquent blade

我正在使用Laravel作为网页的控制器和刀片文件。我的代码类似于:

PropertiesController

$properties = Property::where('status', 1);
$properties = $properties->orderBy('properties.created_at', 'DESC')->paginate(8);
return view('properties.index')->with('properties', $properties);
index.blade.php

中的

@foreach ($properties as $property)
<div class="geo">
  <span class="lat">{{ $property->title }}</span>,
  <span class="lng">{{ $property->description }}</span>
</div>

我想要实现的是获得w.r.t类别。与属性一起计算,为此,我正在做

$properties = Property::where('status', 1);

$categories = array();
if (is_null($req->c)) {
    $search = $properties;
    foreach (Category::all() as $category) {
     array_push(
       $categories,
          array(
            'id' => $category->id,
            'name' => $category->category,
            'counts' => count($search->where('properties.category', $category->id)->get()),
          )
       );
    }
}

$properties = $properties->orderBy('properties.created_at', 'DESC')->paginate(8);

return view('properties.index')->with('properties', $properties)->with('categories', $categories);

$search = $properties;
'counts' => count($search->where('properties.category', $category->id)->get()),

它带给我的是这个 error

试图获得非对象的属性
 <span class="lat"><?php echo e($property->title); ?></span>,

2 个答案:

答案 0 :(得分:2)

我认为您希望将数据传递到刀片视图并获取每个类别的分类数据计数...为此,您可以使用重复的功能分别计算数据。 e.g:

public function properties() {
    $properties = Property::where('status', 1);

    $categories = array();
    foreach (Category::all() as $category) {
        $count = $this->count($category->id);
        array_push(
            $categories,
            array(
                'id' => $category->id,
                'name' => $category->category,
                'counts' => $count,
            )
        );
    }

    $properties = $properties->orderBy('properties.created_at', 'DESC')->paginate(8);

    return view('properties.index')->with('properties', $properties)->with('categories', $categories);
}


public function count($id) {
    $count = count(Property::where('category_id', $id)); // or any variable you are using to connect categories table with
    return $count;
}

$count = $this->count($category->id);

这就是诀窍。

答案 1 :(得分:0)

如果在模型中建立关系,则只能以这种方式使用with()。 这就是控制器的应用方式。

$properties = Property::where('status', 1)->with('category')->orderBy('properties.created_at', 'DESC')->paginate(8);
return view('properties.index', compact('propierties'));

这将为您提供指定类别旁边的属性列表。

但是,如果您需要列出类别并在每个类别中包含属性,则必须执行此操作。

$categories = Category::with('properties')->paginate(8);
return view('properties.index', compact('categories'));