[英]Laravel get All with Relationships and Paginate relationship data
[英]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.