为了账号安全,请及时绑定邮箱和手机立即绑定

如何限制php中的问题?

如何限制php中的问题?

PHP
qq_笑_17 2022-07-22 15:27:46
我使用flutter和php,我只需要从数据库中获取40个随机问题,但我是php的初学者!我该怎么做?见下面的代码public function index(){$user = Auth::user();$topics = Topic::all()->toArray();$questions = Question::all()->toArray();    return response()->json(array('users' =>$user,'topics'=>$topics,'questions'=>$questions), 200);// return response()->json(['data' => $posts], 200, [], JSON_NUMERIC_CHECK);}public function show_question($id){    $topic = Topic::findOrFail($id);    $user_id = Auth::user()->id;    $existing = Answer::where('user_id',$user_id)->where('topic_id',$id)->first();    if($existing == ""){        $topic_ques = Question::where('topic_id', $id)->get()->shuffle();         $questions = $topic_ques->only(40);        return response()->json(array('topic'=>$topic,'questions' => $questions), 200);    }    else{      return response()->json("test already given", 300);      }}
查看完整描述

3 回答

?
慕运维8079593

TA贡献1876条经验 获得超5个赞

public function index(){


$user = Auth::user();

$topics = Topic::all()->toArray();

$questions = Question::all()->random(40)->toArray();


    return response()->json(array('users' =>$user,'topics'=>$topics,'questions'=>$questions), 200);


// return response()->json(['data' => $posts], 200, [], JSON_NUMERIC_CHECK);

}


public function show_question($id){

    $topic = Topic::findOrFail($id);

    $user_id = Auth::user()->id;

    $existing = Answer::where('user_id',$user_id)->where('topic_id',$id)->first();

    if($existing == ""){

        $topic_ques = Question::where('topic_id', $id)->get()->shuffle(); 

        $questions = $topic_ques->only(40);

        return response()->json(array('topic'=>$topic,'questions' => $questions), 200);

    }

    else{

      return response()->json("test already given", 300);  

    }

}


查看完整回答
反对 回复 2022-07-22
?
Helenr

TA贡献1780条经验 获得超4个赞

尝试这个:

$questions = Question::where('topic_id', $id)->inRandomOrder()->take(40)->get();

有关更多信息,请参阅Laravel 文档


查看完整回答
反对 回复 2022-07-22
?
芜湖不芜

TA贡献1796条经验 获得超7个赞

 $topic_ques = Question::where('topic_id', $id)->limit(40)->get()->shuffle();

只需使用限制功能。


查看完整回答
反对 回复 2022-07-22
  • 3 回答
  • 0 关注
  • 183 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号