【问题标题】:Call to undefined method whereHas() in laravel 5.5在 laravel 5.5 中调用未定义的方法 whereHas()
【发布时间】:2018-02-16 10:14:46
【问题描述】:

我正在将我的网站升级并重构为 laravel 5.5,而这段代码目前给我带来了问题。我在 laravel github 文档中进行了搜索,没有发现任何可能影响此的重大更改。

我想做的是我网站中的Related To部分,在每个食谱页面中我想显示更多具有相同类别的食谱。

这是我的代码:

    public static function getRelatedRecipes($recipe){

      $related_category_ids  = $recipe->category()->pluck('categories.id');

        return $relatedRecipes =
        Recipe::whereHas('categories', function ($q)use($related_category_ids){
        $q->whereIn('category_id', $related_category_ids);
        })
        ->where('id', '<>', $recipe->id)
        ->take(4)
        ->inRandomOrder()
        ->get();
}

这是配方模型:

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Recipe extends Model
{
    protected $guarded=[];

    /**
     * Get the route key name for Laravel.
     *
     * @return string
     */
    public function getRouteKeyName()
    {
        return 'slug';
    }



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

}

可能是什么问题?

谢谢,

附言

如果您认为需要任何其他代码来解决此问题,请告诉我,我将在此处发布。 :)

【问题讨论】:

  • Recipe 很可能不是你想象的那样。
  • @Ohgodwhy 食谱是我想的那样,当我 dd($recipe) 我得到完整的食谱。
  • 向我们展示您的Recipe 模型。
  • 多对多关系发生了一些重大变化。还有什么问题?至于你得到什么错误?
  • @Eitan 我没说$recipe 不是你想的那样。我说Recipe 不是你想的那样。该类的完全命名空间路径是什么?它里面有什么关系/

标签: laravel laravel-5 eloquent laravel-5.5


【解决方案1】:

首先确定,你在方法中使用的Recipe是模型,所以不是

Recipe::whereHas('categories', function ($q)use($related_category_ids){

使用

\App\Recipe::whereHas('categories', function ($q)use($related_category_ids){

另一件事是categories 关系。在模型中你没有categories 关系,你只有category 关系

【讨论】:

  • 是的,它总是“小事”。我没有很好地重构。我不得不将类别更改为类别。像魅力一样工作,应该如此。
猜你喜欢
  • 2018-04-12
  • 1970-01-01
  • 2018-03-05
  • 2018-09-29
  • 2018-02-16
  • 1970-01-01
  • 1970-01-01
  • 2013-10-23
  • 1970-01-01
相关资源
最近更新 更多