[英]Display posts in category (Laravel)
I have some tables: 我有一些桌子:
category: 类别:
id: 1 title: Shirt
id: 2 title: Pant
id: 3 title: Hat
product: 产品:
... (product has some columns and 1 col is category_id)
And what I want to display in view is: 我想在视图中显示的是:
1. 5 newest posts for all categories
2. 5 newest posts for each category
Basically, it'll look like: 基本上,它看起来像:
--* Title :All *--
5 Newest posts
--* Title :Shirt *-- -*标题:衬衫*-
5 Newest posts which category_id :1 5最新帖子,其中category_id:1
--* Title :Pant*--
5 Newest posts which category_id :2
--* Title :Hat *-- -*标题:帽子*-
5 Newest posts which category_id :3 5个最新的帖子,其中category_id:3
Any advices, I've searched on google but didn't find the answer :(( 任何建议,我已经在Google上搜索,但没有找到答案:((
Since you have two tables, you'd create two models, one for category and one for product. 由于有两个表,因此将创建两个模型,一个用于类别,一个用于产品。 You can do this by running
php artisan make:model Category
and php artisan make:model Product
您可以通过运行
php artisan make:model Category
和php artisan make:model Product
Now you have these models in your App/ folder. 现在,您的App /文件夹中有这些模型。
Add the following to your category model in App\\Category 将以下内容添加到App \\ Category中的类别模型
public function products()
{
return $this->hasMany('\App\Product', 'category_id', 'id');
}
Go on to the controller that wants to process these data and add at the top 继续到要处理这些数据的控制器,并在顶部添加
use App\Category;
use App\Product;
5 newest posts for all categories 所有类别的5个最新帖子
$product = Product::take(5)->orderBy('id', 'desc')->get(); $ product = Product :: take(5)-> orderBy('id','desc')-> get();
5 newest posts for each category 每个类别5个最新帖子
$categories = Category::get(); $ categories = Category :: get();
foreach ($Categories as $Category) { $products[$Category->name] = $Category->products()->take(5)->orderBy('id', 'desc')->get(); foreach($类别为$ Category){$ products [$ Category-> name] = $ Category-> products()-> take(5)-> orderBy('id','desc')-> get(); }
}
Now to pass this on to the view, i like using a "$data" array, the contents of this array can be accessed directly in the views once passed like so 现在要将其传递给视图,我喜欢使用“ $ data”数组,一旦传递,就可以在视图中直接访问该数组的内容
$data = array();
$data['all_products'] = $product;
$data['category_products'] = $products;
This can then be passed on as 然后可以将其传递为
return View('products.detail', $data);
where products.detail is your view 您在哪里查看product.detail
You can now loop through these data in your view as --* Title :All *-- 您现在可以在视图中以-*标题循环显示所有数据-
@foreach($all_products as $product)
{{$product->name}}
@endforeach
If you have category model like this: 如果您具有这样的类别模型:
class Category extends Model
{
public function posts()
{
return $this->hasMany('\App\Post', 'category_id', 'id');
}
}
You can take 5 Latest post's of every category easily: 您可以轻松地获取每个类别的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.