首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Laravel -在belongsToMany RelationShips上使用inRandomOrder()

Laravel -在belongsToMany RelationShips上使用inRandomOrder()
EN

Stack Overflow用户
提问于 2018-01-19 15:50:42
回答 1查看 1.9K关注 0票数 1

在此代码中,如下所示:

代码语言:javascript
复制
$latestHerbsInformation = \App\ContentCategories::find('14')->contents->take(5);

我想使用inRandomOrder()从内容中获取随机行,ContentsContentCategoriesbelongsToMany RelationShips,代码如下:

代码语言:javascript
复制
$latestHerbsInformation = \App\ContentCategories::find('14')->contents->inRandomOrder()->take(5);

别为我工作。

Contents型号:

代码语言:javascript
复制
class Contents extends Model
{
    use Sluggable;
    protected $table = 'contents';
    protected $guarded = ['id'];

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

ContentCategories型号:

代码语言:javascript
复制
class ContentCategories extends Model
{
    protected $table = 'contents_categories';
    protected $guarded = ['id'];

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

我得到了这个错误:

代码语言:javascript
复制
Method inRandomOrder does not exist. 

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-19 15:52:13

正确的查询是:

代码语言:javascript
复制
\App\ContentCategories::find('14')->contents()->inRandomOrder()->take(5)->get();

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

代码语言:javascript
复制
\App\ContentCategories::find('14')->contents
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48336383

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档