【问题标题】:Laravel Query: How to convert boolean 1 and 0 into 'passed' or 'failed'Laravel 查询:如何将布尔值 1 和 0 转换为“通过”或“失败”
【发布时间】:2021-11-29 22:29:26
【问题描述】:

我目前有一个查询,其中显示测验和参加测验的用户,包括测验的总分、姓名、正确答案的数量,最后是“状态”,即 1 或 0 或通过或失败。

我想在状态中显示它是“通过”还是“失败”而不是 1 或 0。

public function getQuizInfoByQuizID(Request $request, $id){

$remarks = DB::table('user_scores')->where('quiz_id',$id)
->Join('quiz_information','quiz_information.id', '=', 'quiz_id')
->rightJoin('users','users.id', '=', 'user_id')
->select('quiz_information.quiz_title AS Quiz Title','total_points AS Points','number_of_correct_answers',
'users.name AS Name','remarks as STATUS') 
->groupBy('quiz_title','total_points','number_of_correct_answers','name','remarks')
->get()
->toArray();


return response(['message'=>"Remarks successfuly shown", 
'error'=>false,
'error code'=>200,
'line'=>"line".__LINE__."".basename(__LINE__),
'quizRemarks'=>$remarks],200,[],JSON_NUMERIC_CHECK);
}

【问题讨论】:

  • 我认为你可以在 get 函数中处理这个。我在 get 函数中更需要你的代码
  • 有多种方法可以做到这一点,但我认为最好的方法是放弃DB 外观和连接,并使用具有关系的雄辩模型并使用访问器。这将使代码更加清晰

标签: mysql laravel laravel-8


【解决方案1】:

您可以在select 查询中使用if 语句,例如if(remarks=1,"passed","faild")

所以替换这个而不是select:

...->select('quiz_information.quiz_title AS Quiz Title','total_points AS Points','number_of_correct_answers',
'users.name AS Name',DB::raw('if(remarks=1,"passed","faild") as STATUS')) 

但是你可以使用模型(Eloquent),然后使用访问器(Eloquent accessor)。

【讨论】:

  • 我收到此错误Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version
  • 对不起。存在语法问题,已修复并更新答案
  • 工作。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-28
  • 1970-01-01
  • 2017-09-27
  • 2020-11-27
  • 2013-10-07
  • 1970-01-01
  • 2021-07-25
相关资源
最近更新 更多