我是laravel的新手,请原谅我可能出现的问题。此外,我确实调查了所有其他“类似”的问题,但要么他们不能重现正确的解决方案,要么我老实说我很难绕过它。
情景:
我有一个Post模型和一个Subject模型。这就是他们目前的样子。
Post.php中的
public function subjects() {
return $this->belongsToMany('Subject', 'posts_subjects');
}
在Subject.php中
public function posts() {
return $this->belongsToMany('Post', 'posts_subjects');
}
现在,我需要实现的是:
如果将查询参数传递给请求(即q = Food),我想仅返回其主题关系中包含主题食物的帖子而不返回其他帖子。如果没有通过,那么我只是展示一切......
这就是我的PostsController的索引操作看起来像atm。
public function index() {
$q = Input::get('q');
$posts = Post::all();
return View::make('posts.index', ['posts' => $posts]);
}
我将如何做到这一点?非常感谢一些帮助。 非常感谢
PS。我可以使用此代码获取所有帖子。
答案 0 :(得分:2)
这是未经测试的代码,但如果您的查询只返回一个主题,它可能适合您:
public function index()
{
if($q = Input::get('q'))
{
if($subject = Subject::with('posts')->where('name', $q)->first())
{
$posts = $subject->posts;
}
else
{
$posts = array();
}
}
else
{
$posts = Post::all();
}
return View::make('posts.index', ['posts' => $posts]);
}