【问题标题】:Laravel query with hasmany relationship具有hasmany关系的Laravel查询
【发布时间】:2014-03-18 20:14:38
【问题描述】:

我是 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]);
}

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

附言。我可以使用此代码获取所有帖子。

【问题讨论】:

  • 我认为您可能对这些关系的运作方式有些困惑。一个帖子可以有多个主题(一个帖子可以与食物和旅行相关联吗)?
  • 使用数据透视表的多对多关系意味着在关系的两边都使用belongsToMany()
  • 是的,对不起。我确实(并且确实)在两个模型上都有 belongsToMany .. 我只是稍微改变了一下,认为我可能做错了什么,但问题仍然存在.. 我可以从主题模型中获取给定主题的帖子,但因为它我们正在谈论的 PostsController,将整个返回值基于不同的模型感觉很奇怪..

标签: laravel laravel-4 eloquent


【解决方案1】:

这是未经测试的代码,但如果该查询仅返回一个主题,它可能对您有用:

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

【讨论】:

  • 谢谢老兄。这做到了:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-22
  • 1970-01-01
  • 2021-10-07
  • 1970-01-01
  • 2016-07-12
  • 2018-06-12
  • 2019-06-02
相关资源
最近更新 更多