【问题标题】:Laravel: Get relationship in randomized orderLaravel:以随机顺序获取关系
【发布时间】:2017-05-12 14:57:10
【问题描述】:

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

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

我想以随机顺序返回answers

我的表结构是:

questions

answers

answer_questions - question_id, answer_id

有什么想法吗?

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    这应该可行:

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

    我在答案关系上调用了 inRandomOrder(这样答案将被随机排序)以及问题,所以这个查询将返回 1 个随机问题,其中所有答案都是随机排序的。

    【讨论】:

      【解决方案2】:

      试试这个:

      $question= Question::inRandomOrder()->first();
      $randomAnswer= $question->answers()->random();
      

      【讨论】:

      • 这对我有用,但我必须添加 get(): Question::inRandomOrder()->first()->answers()->get()->random()
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多