Laravel:以随机顺序获取关系

标签 laravel eloquent

我有以下代码,我得到一个随机问题及其答案:

$q = Question::with('answers')
        ->inRandomOrder()
        ->first();

我想以随机顺序返回答案

我的表结构是:

问题

答案

answer_questions - Question_id、answer_id

有什么想法吗?

最佳答案

这应该有效:

$q = Question::with(['answers' => function ($q) {
    $q->inRandomOrder();
}])->inRandomOrder()->first();

我对答案关系(以便答案随机排序)和问题调用了 inRandomOrder,因此此查询将返回 1 个随机问题,其所有答案均随机排序。

关于Laravel:以随机顺序获取关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41360122/

相关文章:

php - openssl 扩展丢失(Composer 安装 openSUSE)

mysql - 如何在Laravel 5中处理BIT数据类型?

php - BadMethodCallException:方法 Illuminate\Database\Eloquent\Collection::orderBy 不存在

mysql - Laravel Eloquent : Alphabetical Order but from Small words to Sentence

php - 不允许序列化 'Closure' - laravel

mysql - Laravel 5.1 - Homestead MySQL 连接。 `Connection Refused` & `No such file or directory`

php - 基于多对多关系与同一列上的多个条件进行搜索

php - Laravel (nova) 继承映射

php - Laravel/Eloquent - 查询 - 选择关系

php - Laravel 子查询问题,使用 whereIn 时获取最新行