显示分类中的帖子(Laravel)

时间:2016-09-11 16:53:18

标签: php laravel laravel-5

我有一些表格:

类别:

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

任何建议,我都在谷歌搜索但没有找到答案:((

2 个答案:

答案 0 :(得分:1)

由于您有两个表,因此您需要创建两个模型,一个用于类别,另一个用于产品。您可以通过运行php artisan make:model Categoryphp artisan make:model Product

来执行此操作

现在你的App /文件夹中有这些模型。

将以下内容添加到App \ Category

中的类别模型中
public function products()
    {
        return $this->hasMany('\App\Product', 'category_id', 'id');
    }

转到想要处理这些数据的控制器并在顶部添加

use App\Category;
use App\Product;
  1. 所有类别的5条最新帖子

    $ product = Product :: take(5) - > orderBy(' id',' desc') - > get();

  2. 每个类别的5个最新帖子

    $ categories = Category :: get();

    foreach($ Categories as $ Category){     $ products [$ Category-> name] = $ Category-> products() - > take(5) - > orderBy(' id',' desc') - >得到(); }

  3. 现在将此传递给视图,我喜欢使用" $ data"数组,这个数组的内容可以直接在视图中一次性访问

    $data =  array();
    $data['all_products'] = $product;
    $data['category_products'] = $products;
    

    然后可以将其作为

    传递
    return View('products.detail', $data);
    

    其中products.detail是您的观点

    您现在可以在视图中循环浏览这些数据了 - *标题:全部* -

    @foreach($all_products as $product)
    {{$product->name}}
    @endforeach
    

答案 1 :(得分:0)

如果你有这样的类别模型:

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
}
相关问题