![](/img/trans.png)
[英]I want to display username of comment's owner, however, comments table has user_id only
[英]How can I combine a table that has two user_id and display in a view
我在Laravel有一個觀點問題
比方說
User
id|user_name|
1 |Amy|
2 |Bob|
3 |Candy|
4 |Dina|
5 |Edwin|
Product
id|product_name|
1 |iPhone 10|
2 |Galaxy 10|
3 |Huawei P10|
4 |Vivo R10|
5 |Xiaomi 10|
Q&A
id| Question | Answer |ask_user_id|ans_user_id|Product_id|
1 |Question 1|Answer For Q1| 5 | 1 | 1 |
2 |Question 2|Answer For Q2| 4 | 2 | 3 |
3 |Question 3|Answer For Q3| 3 | 4 | 3 |
4 |Question 4|Answer For Q4| 2 | 4 | 4 |
5 |Question 5|Answer For Q5| 1 | 5 | 5 |
我想讓用戶提出問題,並讓用戶回答問題。
因此,控件為:
public function getProductDetail($id) {
/*
Get Questions and Answers Q&A section
*/
//Get questions here
$sql = "SELECT USER.user_name as askUser, QA.question as theQuestion, QA.date_of_post FROM USER, QA WHERE id IN (SELECT ask_user_id FROM QA WHERE product_id = ?) AND USER.id = QA.ask_user_id";
$questions = DB::select($sql, array($id));
//Get answers here
$sql = "SELECT USER.user_name as ansUser, QA.answer FROM USER, QA WHERE id IN (SELECT ans_user_id FROM QA WHERE product_id = ?)AND USER.id = QA.ans_user_id";
$answers = DB::select($sql, array($id));
return view('includes.products.productDetail',
['questions' => $questions, 'answers' => $answers]);
}
在視圖中,我編寫了如下代碼:
<div class="QA">
<h2>Questions and Answers</h2>
<div class="question">
<ul class="list-unstyled">
@foreach($questions as $question)
<div class="shadow p-3 mb-5 bg-white rounded">
<li>{{ $question -> theQuestion }}</li>
<li>{{ $question -> askUser }} asked on {{ $question -> date_of_post}}</li>
</div>
@endforeach
@foreach($answers as $answer)
<li>{{ $answer -> answer }}</li>
<li>{{ $answer -> ansUser}}</li>
@endforeach
</ul>
</div>
</div>
我嘗試了不同的方法,但是問題和結果始終分開顯示。 我希望它們以以下格式顯示:
Q&A
Question 1
author
Answer section
ansUser1 answer
ansUser2 answer
_________________
Question 2
author
Answer section
ansUser3 answer
ansUser4 answer
_________________
Question 3
author
Answer section
ansUser2 answer
ansUser3 answer
我不確定問題是來自我的觀點還是來自SQL。 欣賞!!
一種實現方法是循環每個問題的所有答案,然后檢查答案是否與問題匹配。 (不是最好的方法,但是仍然可以)
為此,請在答案查詢中獲取問題ID
$sql = "SELECT USER.user_name as ansUser, QA.answer, QA.question, FROM USER, QA WHERE id IN (SELECT ans_user_id FROM QA WHERE product_id = ?)AND USER.id = QA.ans_user_id";
然后更改foreach循環
@foreach($questions as $question)
<div class="shadow p-3 mb-5 bg-white rounded">
<li>{{ $question -> theQuestion }}</li>
<li>{{ $question -> askUser }} asked on {{ $question -> date_of_post}}</li>
@foreach($answers as $answer)
@if($answer->question == $question->theQuestion)
<li>{{ $answer -> answer }}</li>
<li>{{ $answer -> ansUser}}</li>
@endif
@endforeach
</div>
@endforeach
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.