簡體   English   中英

Laravel獲取和分頁相同的數據

[英]Laravel get and paginate same data

我將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>

我要實現的是獲取帶有屬性的wrt計數,為此,我正在做

$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()),

有了它,它給了我 錯誤

試圖獲取非對象的屬性
<span class="lat"><?php echo e($property->title); ?></span>,

我認為您想將數據傳遞到刀片視圖並獲取每個類別的分類數據的計數……為此,您可以使用重復函數分別對數據進行計數。 例如:

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);

這是成功的訣竅。

如果在模型中建立了關系,則只能以這種方式與()一起使用。 這就是控制器的方式。

$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'));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM