![](/img/trans.png)
[英]Laravel 5.1 Eloquent with() and max() using multiple has-many relationships
[英]Laravel Insert Data with Two Has Many Relationships using Eloquent
我已經嘗試了10次,但仍然無法做到。 所以這就是我想做的。
我正在嘗試插入一個具有多個問題的測驗,並且每個問題具有多個選項 。
測驗 - 有很多 -> 問題 - 有很多 -> 選項
例如:
This is a Quiz?
Question 1?
Option 1
Option 2
Question 2?
Option 1
Option 2
我有3張桌子來存儲Quiz Questions and Answers
。 它們都已正確鏈接,我可以毫無問題地獲取並顯示測驗。
但我想參加測驗。 我知道如何以單個插入數據有很多關系,但是絕對不知道如何以2個或多個插入數據有很多關系。
$quiz = new Quiz;
...
$quiz->save();
$questions = [new Question, new Question, ...];
$quiz->questions()->saveMany($questions);
我能夠插入測驗和與該測驗相關聯的多個問題,但現在我也想為每個問題插入多個選項,例如$options1, $options2
等。
我是Laravel的新手。
您將需要這樣的東西
class Quiz extends Eloquent {
protected $table = "you table name here";
public function questions() {
return $this->hasMany("Question", "question_id", "id");
//where Question is your model for questions table
}
}
class Question extends Eloquent {
protected $table = "you table name here";
}
$quiz = new Quiz;
//set quiz data here
// $quiz->name = "name";
$quiz->save();
for ($i = 0; $i < count($questions); $i++) {
$arr[$i] = new Question;
$arr[$i]->quize_id = $quiz->id;;
// Set other data here
}
$quiz->questions()->saveMany($arr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.