【发布时间】: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