【问题标题】:Laravel 5.4 how to get Articles related to a CategoryLaravel 5.4 如何获取与类别相关的文章
【发布时间】:2018-12-11 03:07:40
【问题描述】:

我正在 Laravel 5.4 中构建一个简单的商店目录。基本上,我想要的是在我的文章上有一个按钮,用于获取所有具有相关类别的文章(注意一篇文章可以有很多类别)。

我有我的文章和类别模型,以及 article_category 数据透视表。两者都有属于多方的关系,例如:

文章模型中的代码:

public function categories()
{
    return $this->belongsToMany('App\Category');
}

类别模型代码:

public function articles()
{
    return $this->belongsToMany('App\Article');
}

我的问题是如何获取包含与文章相关类别的所有文章的文章列表。

这是我现在在控制器上的函数,它接收一个带有类别列表的 JSON 对象:

public function showRelatedArticles($category) 
{
    // Decode JSON to PHP array
    $category = json_decode($category);
    $collection;
    if(is_array($category)){
        foreach ($category as $cat) {
            $articles = Article::whereHas('Category', function ($query) {
                $query->where('category_id', $cat->id);
            })->get();
            $collection = merge($articles);
        }
    } else {
        dd('Not array');
    }

    return view('front', ['articles' => $collection]);
}

这会返回一个错误:

BadMethodCallException
调用未定义的方法 Illuminate\Database\Query\Builder::Category()

我的模型之间可能有错误的关系类型,但这是声明多对多关系的正确方法,不是吗?

【问题讨论】:

  • whereHas('categories',?
  • 感谢 Felippe Duarte,您可能会有所收获,我应该使用“类别”而不是“类别”。不幸的是,我似乎无法在函数中使用 $cat,它给了我一个“未定义的变量”错误。将第二个参数传递给函数似乎会破坏它,我应该如何进行?
  • function ($query) use($cat) {

标签: php laravel laravel-5 eloquent


【解决方案1】:

您可以将整个部分重写为:

if (is_array($category)){
    $category_ids = collect($category)->pluck('id');

    $articles = Article::whereHas('categories', function($query) use ($category_ids) {
        // Assuming your category table has a column id
        $query->whereIn('categories.id', $category_ids);
    })->get();
} else {
    dd('Not array');
}

注意小写的categories,它是Article类中的函数名。

这结合了查询中的 in 和数组中的 collect,并且只检索链接到给定类别的文章。

【讨论】:

  • 这在 $query->where('id', 'in', $category_ids); 上给了我一个“未定义的变量 $category_ids”;可能是进入函数时超出范围?
  • @TianRB 是的,函数后面的使用部分忘记了。已添加!
  • 嗯,它肯定在向前发展!我收到错误 SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where 子句不明确(SQL: select * from articles where exists (select * from categories inner join article_category on @ 987654329@.id = article_category.category_id 其中articles.id = article_category.article_idid = in))
  • 太棒了!将where('id', 'in' 更改为where('categories.id', 'in',我们应该在那里!
  • @TianRB 但我们不是。我忘记了在 5.4 中它是 whereIn 而不是 where(... in。更新了答案。
猜你喜欢
  • 2021-12-22
  • 1970-01-01
  • 2019-10-10
  • 2014-01-20
  • 1970-01-01
  • 1970-01-01
  • 2021-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多