我有3张桌子
user: id, username
subreddits: id, name, created_at
posts: id, title, link, user_id, subreddit_id
问题是,我手动获取 subreddit/类别的 id,而我需要动态获取它。我怎样才能做到这一点?
这是show()
SubredditController.php 中的方法
public function show(Subreddit $subreddit)
{
$posts = Subreddit::findOrFail(3)->posts()->get();
return view('subreddit/show')->with('subreddit', $subreddit)
->with('posts', $posts);
}
这是 Subreddit 模型
class Subreddit extends Model
{
protected $fillable = [
'name',
'description'
];
public function user() {
return $this->belongsTo('App\User');
}
public function posts() {
return $this->hasMany('App\Post');
}
}
路线.php
Route::resource('subreddit', 'SubredditController');
Route::resource('posts', 'PostsController');
路由服务提供商.php
$router->model('articles', 'App\Article');
$router->model('subreddit', 'App\Subreddit');
$router->model('posts', 'App\Post');