Laravel - 在belongsToMany RelationShips上使用inRandomOrder()

时间:2018-01-19 07:50:42

标签: php laravel laravel-5.5

在此代码中:

$latestHerbsInformation = \App\ContentCategories::find('14')->contents->take(5);

哪种工作正常我想使用inRandomOrder()从内容中获取随机行ContentsContentCategoriesbelongsToMany RelationShips,此代码为:

$latestHerbsInformation = \App\ContentCategories::find('14')->contents->inRandomOrder()->take(5);

不适合我。

Contents型号:

class Contents extends Model
{
    use Sluggable;
    protected $table = 'contents';
    protected $guarded = ['id'];

    public function categories()
    {
        return $this->belongsToMany(ContentCategories::class);
    }
}

ContentCategories型号:

class ContentCategories extends Model
{
    protected $table = 'contents_categories';
    protected $guarded = ['id'];

    public function contents()
    {
        return $this->belongsToMany(Contents::class);
    }
}

我收到此错误:

Method inRandomOrder does not exist. 

我该如何解决这个问题?提前致谢

1 个答案:

答案 0 :(得分:2)

正确的查询是:

\App\ContentCategories::find('14')->contents()->inRandomOrder()->take(5)->get();

因为这会执行查询并返回一个集合:

\App\ContentCategories::find('14')->contents