在此代码中:
$latestHerbsInformation = \App\ContentCategories::find('14')->contents->take(5);
哪种工作正常我想使用inRandomOrder()
从内容中获取随机行Contents
和ContentCategories
为belongsToMany 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.
我该如何解决这个问题?提前致谢
答案 0 :(得分:2)
正确的查询是:
\App\ContentCategories::find('14')->contents()->inRandomOrder()->take(5)->get();
因为这会执行查询并返回一个集合:
\App\ContentCategories::find('14')->contents