[英]Display posts in category (Laravel)
我有一些桌子:
类别:
id: 1 title: Shirt
id: 2 title: Pant
id: 3 title: Hat
产品:
... (product has some columns and 1 col is category_id)
我想在视图中显示的是:
1. 5 newest posts for all categories
2. 5 newest posts for each category
基本上,它看起来像:
--* Title :All *--
5 Newest posts
-*标题:衬衫*-
5最新帖子,其中category_id:1
--* Title :Pant*--
5 Newest posts which category_id :2
-*标题:帽子*-
5个最新的帖子,其中category_id:3
任何建议,我已经在Google上搜索,但没有找到答案:((
由于有两个表,因此将创建两个模型,一个用于类别,一个用于产品。 您可以通过运行php artisan make:model Category
和php artisan make:model Product
现在,您的App /文件夹中有这些模型。
将以下内容添加到App \\ Category中的类别模型
public function products()
{
return $this->hasMany('\App\Product', 'category_id', 'id');
}
继续到要处理这些数据的控制器,并在顶部添加
use App\Category;
use App\Product;
所有类别的5个最新帖子
$ product = Product :: take(5)-> orderBy('id','desc')-> get();
每个类别5个最新帖子
$ categories = Category :: get();
foreach($类别为$ Category){$ products [$ Category-> name] = $ Category-> products()-> take(5)-> orderBy('id','desc')-> get(); }
现在要将其传递给视图,我喜欢使用“ $ data”数组,一旦传递,就可以在视图中直接访问该数组的内容
$data = array();
$data['all_products'] = $product;
$data['category_products'] = $products;
然后可以将其传递为
return View('products.detail', $data);
您在哪里查看product.detail
您现在可以在视图中以-*标题循环显示所有数据-
@foreach($all_products as $product)
{{$product->name}}
@endforeach
如果您具有这样的类别模型:
class Category extends Model
{
public function posts()
{
return $this->hasMany('\App\Post', 'category_id', 'id');
}
}
您可以轻松地获取每个类别的5个最新帖子:
$Categories = Category::get();
foreach ($Categories as $Category) {
$Posts = $Category->posts()->take(5)->orderBy('id', 'desc')->get(); // Get 5 Posts
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.