Laravel - 按ID

时间:2016-08-30 08:36:48

标签: php laravel laravel-5.2

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

我们说我有一个类别是Javascript'我只想在页面上显示带有javascript类别的帖子。

执行此操作的正确代码是什么?这是一个例子,大胆的' javascript'是需要用正确的代码替换的东西。

- categoriesController.php ---

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

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

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

1 个答案:

答案 0 :(得分:1)

例如: post.php模型     class Post扩展了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

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