我正在将我的网站升级并重构为 laravel 5.5,而这段代码目前给我带来了问题。我在 laravel github 文档中进行了搜索,没有发现任何可能影响此的重大更改。
我想做的是与我网站中的相关部分,在每个食谱页面中,我想显示更多具有相同类别的食谱。
这是我的代码:
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');
}
}
可能是什么问题呢?
谢谢,
附言
如果您认为需要任何其他代码来解决此问题,请告诉我,我将在此处发布。:)