Laravel-按ID显示类别 [英] Laravel - displaying categories by id

查看:51
本文介绍了Laravel-按ID显示类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于博客网站,我拥有所有帖子&页面上显示的类别列表,但是现在我需要在其自己的单独页面上显示每个类别的帖子.

For a blog site, I have all the posts & lists of categories displaying on a page though now I need to display the posts for each category on it's own separate page.

比方说,我的类别是"Javascript",我只希望页面上显示具有javascript类别的帖子.

Let's say I had a categorie that was 'Javascript' and I wanted only the posts with the category of javascript displayed on a page.

执行此操作的正确代码是什么?这是一个示例,需要用正确的代码替换粗体的"javascript".

What's the correct code to do this? here's an example, the bold 'javascript' is what needs to be replaced with the correct code.

-CategoriesController.php ---

-- categoriesController.php ---

public function show($id)
{
$post->withCategories($Categories)->$id->($id as **javascript)**
}

--- javascript.blade.php ---(对应视图)

--- javascript.blade.php --- ( corresponding view )

<tbody>
@foreach ($categories as $category->$id>**javascript**)
<tr>
<th>{{ $category->id }}</th>
<td>{{ $category->name }}</td>
</tr>
@endforeach
</tbody>
</table>
</div> <!-- end of .col

推荐答案

例如: post.php模型 类Post扩展Model { 保护的$ primaryKey ='id';

For example: post.php model class Post extends Model { protected $primaryKey = 'id';

    function withCategories() {
       return $this->hasOne('App\Categories', 'id', 'category_id');
    }

    public function show($id){
         Post::with('withCategories')->where('category_id', $id)->get(); //the output of articles of the category
    }
}

$ id是url的参数:site.com/posts/javascript

$id is a parameter of url: site.com/posts/javascript

在posts.blade.php

in posts.blade.php

<table>
<tbody>
@foreach ($posts as $post)
<tr>
<th>{{ $post->id }}</th>
<td>{{ $post->name }}</td>
<td>{{ $post->withCategories->name }}</td> <!-- Category name-->
</tr>
@endforeach
</tbody>
</table>
</div>

这篇关于Laravel-按ID显示类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆