用户 - >有很多疑问 问题 - >有很多答案
我想向每位用户展示一个问题信息以及每个问题的最新答案
$questions = Question::select('id','user_id',
'title','video','status','created_at')
->where('user_id','=',$user->id)
->where('status','>=','2')
->with([
'user' => function($query){
$query->select('id','name','picture');
},
'answers' => function($query){
$query->select('id','question_id','user_id','answer','created_at',DB::raw('count(*) as answer_count'))
->orderBy('created_at','desc')->first();
},
])->get();
这里我没有得到每个问题的答案。我得到了用户提交的所有问题的答案
你可以帮帮我吗?如何将置于问题ID以供回答User [id, name, and so on ] ->
question [
['id', 'title' ..]->Answer['id','question_id',etc ],
['id', 'title' ..]->Answer['id','question_id',etc ]
]
答案 0 :(得分:0)
您需要首先向用户提出他们的问题及其答案,而不是问题本身,以获得预期的输出:
echo 'Array Total<pre>';
$sum = 0;
foreach ( $receipt_data['results'] as $receipt )
{
$sum += $receipt['total'];
}
echo '</pre>';
现在,您应该可以通过以下方式获取给定用户提出的所有问题及其最新答案:
$user = User::select('id','name','picture')->with([
'questions' => function($query){
$query->select('id','user_id','title','video','status','created_at');
$query->where('status','>=','2');
},
'questions.answers' => function($query){
$query->select('id','question_id','user_id','answer','created_at',DB::raw('count(*) as answer_count'));
$query->orderBy('created_at','desc')->first();
},
])->findOrFail($user_id);
答案 1 :(得分:0)
$questions = Question::select('id','user_id','title','video','status','created_at')->with([
'user' => function($query){
$query->select('id','name','picture');
}
])->where('status','>=','2')->get();
foreach($questions as $question)
{
$question_data[] = [
'id' => $question->id,
'title' => $question->title,
'video' => $question->video,
'user_id' => $question->user_id,
'status' => $question->status,
'created_at' => $question->created_at->toDateTimeString(),
'thumbnail' => $question->thumbnail,
'user' => [
'id' => $question->user->id,
'name' => $question->user->name,
'picture' => $question->user->picture
],
'answers' =>
$question->answers()->select('video','question_id','user_id','created_at','thumbnail')
->with([
'user' => function($query){
$query->select('id','name','picture');
}
])->orderBy('created_at','desc')->first()];
}