此API路由工作正常并返回JSON响应,目前它将category_id
作为外键返回,我还希望获得列名称'来自表'类别'在我的JSON响应中,该怎么做?应该感谢帮助。
Route::get('/quizzes', function() {
$quizzes = App\Quiz::select('id','name','description','average_playtime','status','image','thumbnail','created_at','updated_at','category_id','user_id','category_name'
DB::raw('created_at >= DATE_SUB(CURDATE(),INTERVAL 10 day) as isNew')
)->where('status', 'active')->take(20)->get();
return Response::json(array(
'error' => false,
'quizzes' => $quizzes,
'status_code' => 200
));
});
答案 0 :(得分:0)
加入表类别并获取category_name
Route::get('/quizzes', function() {
$quiz = new App\Quiz();
$selectClause = array(
$quiz.getTable().'id',
$quiz.getTable().'name',
$quiz.getTable().'description',
$quiz.getTable().'average_playtime',
$quiz.getTable().'status',
$quiz.getTable().'image',
$quiz.getTable().'thumbnail',
$quiz.getTable().'created_at',
$quiz.getTable().'updated_at',
$quiz.getTable().'category_id',
$quiz.getTable().'user_id',
'c.category_name',
DB::raw($quiz.getTable().'created_at >= DATE_SUB(CURDATE(),INTERVAL 10 day) as isNew')
);
$quizzes = App\Quiz::join('category AS c', 'c.category_id', '=', $quiz.getTable().'category_id')
->select($selectClause)
->where('status', 'active')
->take(20)
->get();
return Response::json(array(
'error' => false,
'quizzes' => $quizzes,
'status_code' => 200
));
});