2014-03-18 87 views
2

我是新来laravel所以原谅我可能noobish问题。另外,我也研究过所有其他'类似'的问题,但要么他们没有重现正确的解决方案,要么我老实说很难将其解决。Laravel查询用的hasMany关系

该场景:

我有一个Post模型和一个Subject模型。这是他们目前的样子。

在post.php中

在Subject.php

public function subjects() { 
    return $this->belongsToMany('Subject', 'posts_subjects'); 
} 

现在

public function posts() { 
    return $this->belongsToMany('Post', 'posts_subjects'); 
} 

,我需要实现的是:

如果一个查询参数传递给请求(即q =食物)我只想返回包含受试者关系中的主题食物的帖子,而不是其他人。如果没有通过,则只需显示一切......

这是我的PostsController的index动作看起来就像个大气压。

public function index() { 

    $q = Input::get('q'); 

    $posts = Post::all(); 

    return View::make('posts.index', ['posts' => $posts]); 
} 

我该怎么做呢?将不胜感激一些帮助。 非常感谢

PS。我可以通过此代码获取所有帖子。

+0

我想你可能是如何的关系是工作有点混乱。单个帖子是否可以有很多主题(单个帖子是否可以与食品和旅行相关联)? – user3158900

+0

使用数据透视表的多对多关系意味着在关系的两边使用'belongsToMany()'。 –

+0

是的,对不起。我做(做)有belongsToMany两种型号..我只是改变了一些事情了一下周围想我可能做错了什么,但问题仍然..我能得到的职位从主题模型,但因为给定的主题我们谈论的PostsController,感觉怪异立足于一个不同的模型.. –

回答

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]); 
} 
+0

谢谢老兄整个返回值。这样做:) –