0
laravel使用雄辯從數據庫中獲取數據。作爲相關行下的數組映射連接結果
我有兩個表「問題」和「選項」 現在用雄辯的方法來連接「選項」到「問題」
$questions = Question::join('options', 'options.question_id', 'questions.id');
return QuestionResource($questions);
這不會返回數據,其中同一個問題的預期集合在集合中多次出現,並且每個「options.question_id」和「question.id」都是相同的不同選項。
[
{
id: 1,
text: "Africa is a...?",
// joined option
question_id: 1,
value: "city",
answer: false
},
{
id: 1,
text: "Africa is a...?",
// joined option
question_id: 1,
value: "planet",
answer: false
},
{
id: 1,
text: "Africa is a...?",
// joined option
question_id: 1,
value: "continent",
answer: true
},
{
id: 2,
text: "Albert Heinstein was a...?",
// joined option
question_id: 2,
value: "comedian",
answer: false
},
{
id: 2,
text: "Albert Heinstein was a...?",
// joined option
question_id: 1,
value: "genius scientist",
answer: true
}
]
我希望所有選項都嵌套在相關問題的關鍵字下。像
[
{
id: 1,
text: "Africa is a...?",
// joined options
options: [
{value: "city", answer: false},
{value: "planet", answer: false},
{value: "continent", answer: true}
]
},
{
id: 2,
text: "Albert Heinstein was a...?",
// joined options
options: [
{value: "comedian", answer: false},
{value: "genius scientist", answer: true}
]
}
]
我可以用laravel雄辯實現這一目標,不然我就必須申請一個額外的邏輯。
你需要PHP簡單循環內準備數組,您在'$ questions'收到陣列的集合變量並傳遞導致陣列作爲迴應。或者,如果您使用的是簡單的'ORM'結構,那麼只需在'Question'模型中準備一個關係,並且您可以使用'with'或'load'方法或直接調用來獲得該關係 –