laravel 分类的列表查询

public function index(Request $request, ResponseFactoryContract $response, QuestionModel $questionModel)
{
$userID = $request->user('api')->id ?? 0;
$limit = max(1, min(30, $request->query('limit', 15)));
$offset = max(0, $request->query('offset', 0));
$subject = $request->query('subject');
$map = [
'all' => function ($query) {
$query->orderBy('id', 'desc');
},
'new' => function ($query) {
$query->where('answers_count', 0)
->orderBy('id', 'desc');
},
'hot' => function ($query) use ($questionModel) {
$query->whereBetween('created_at', [
$questionModel->freshTimestamp()->subMonth(1),
$questionModel->freshTimestamp(),
])->where('answers_count', '!=', 0);
$query->orderBy('answers_count', 'desc');
},
'reward' => function ($query) {
$query->where('amount', '!=', 0)
->orderBy('id', 'desc');
},
'excellent' => function ($query) {
$query->where('excellent', '!=', 0)
->orderBy('id', 'desc');
},
'follow' => function ($query) use ($userID) {
$query->whereExists(function ($query) use ($userID) {
$query->from('question_watcher')
->where('question_watcher.user_id', '=', $userID)
->whereRaw('question_watcher.question_id = questions.id');
});
},
];
$type = in_array($type = $request->query('type', 'new'), array_keys($map)) ? $type : 'new';
call_user_func($map[$type], $query = $questionModel
->whereDoesntHave('blacks', function ($query) use ($userID) {
$query->where('user_id', $userID);
})
->when($subject, function ($query) use ($subject) {
return $query->where('subject', 'like', '%'.$subject.'%');
})
->limit($limit)
->offset($offset));
$questions = $query->get();
$questions->load('user');

return $response->json($questions->map(function (QuestionModel $question) use ($userID) {
if ($question->anonymity && $question->user_id !== $userID) {
$question->addHidden('user');
$question->user_id = 0;
}

$question->answer = $question->answers()
->whereDoesntHave('blacks', function ($query) use ($userID) {
$query->where('user_id', $userID);
})
->with('user')
->orderBy('id', 'desc')
->first();

if ($question->answer) {
if ($question->answer->anonymity && $question->answer->user_id !== $userID) {
$question->answer->addHidden('user');
$question->answer->user_id = 0;
}
$question->answer->liked = (bool) $question->answer->liked($userID);
$question->answer->collected = (bool) $question->answer->collected($userID);
$question->answer->rewarded = (bool) $question->answer->rewarders()->where('user_id', $userID)->first();
$question->look && $question->answer->could = true;

if ($question->look && $question->answer->invited && (! $question->answer->onlookers()->where('user_id', $userID)->first()) && $question->answer->user_id !== $userID && $question->user_id !== $userID) {
$question->answer->could = false;
$question->answer->body = null;
}
}

return $question;
}))->setStatusCode(200);
}
posted @ 2019-02-20 17:39  心之所依  阅读(1133)  评论(0编辑  收藏  举报