Laravel 5:如何检索并显示属于某一类别的所有帖子 [英] Laravel 5: how can I retrieve and display all posts that belong to certain category
问题描述
我有3个表
user:id,username
subreddits:id,name,created_at
帖子:id,title,link,user_id,subreddit_id
问题是,我正在获取id的subreddit / category手动,而我需要动态获取它。如何实现?
这是SubredditController.php中的 show()
方法
public function show(Subreddit $ subreddit)
{
$ posts = Subreddit :: findOrFail(3) - >的帖子() - >获得();
返回视图('subreddit / show') - >与('subreddit',$ subreddit)
- >与('posts',$ posts);
}
这是Subreddit Model
class Subreddit extends Model
{
protected $ fillable = [
'name',
'description'
]。
public function user(){
return $ this-> belongsTo('App\User');
}
public function posts(){
return $ this-> hasMany('App \Post');
}
}
routes.php
Route :: resource('subreddit','SubredditController');
Route :: resource('posts','PostsController');
RouteServiceProvider.php
$ router-> model('articles','App'\\Article');
$ router-> model('subreddit','App \Subreddit');
$ router-> model('posts','App \Post');
正如使用路由模型绑定一样,Laravel会自动检索URI中提供的$ id的对象,然后可以使用依赖注入作为参数注入到您的方法中。
public function show(Subreddit $ subreddit){...}
pre>
您可以像任何对象一样访问数据。例如。要访问记录的ID,您可以使用
$ subreddit-> id
。public function show(Subreddit $ subreddit)
{
$ posts = Subreddit :: findOrFail($ subreddit-> id) - > posts() - > get();
返回视图('subreddit / show') - >与('subreddit',$ subreddit)
- >与('posts',$ posts);
}
I have 3 tables
user: id, username subreddits: id, name, created_at posts: id, title, link, user_id, subreddit_id
The problem is, I am fetching the id of the subreddit / category manually while I need to be fetching it dynamically. How can I achieve that?
This is the
show()
method in SubredditController.phppublic function show(Subreddit $subreddit) { $posts = Subreddit::findOrFail(3)->posts()->get(); return view('subreddit/show')->with('subreddit', $subreddit) ->with('posts', $posts); }
And this is Subreddit Model
class Subreddit extends Model { protected $fillable = [ 'name', 'description' ]; public function user() { return $this->belongsTo('App\User'); } public function posts() { return $this->hasMany('App\Post'); } }
routes.php
Route::resource('subreddit', 'SubredditController'); Route::resource('posts', 'PostsController');
RouteServiceProvider.php
$router->model('articles', 'App\Article'); $router->model('subreddit', 'App\Subreddit'); $router->model('posts', 'App\Post');
解决方案As you are using Route Model Binding, Laravel will automatically retrieve an object for the $id provided in the URI, which can then be injected into your method as an argument using dependency injection.
public function show(Subreddit $subreddit){ ... }
You can access the data as you would any object. E.g. To access the id of the record you can use
$subreddit->id
.public function show(Subreddit $subreddit) { $posts = Subreddit::findOrFail($subreddit->id)->posts()->get(); return view('subreddit/show')->with('subreddit', $subreddit) ->with('posts', $posts); }
这篇关于Laravel 5:如何检索并显示属于某一类别的所有帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!