2017-08-14 71 views
0

如何使用Laravel Eloquent在一行中保存此問題答案關係船模型。如果這是不可能的,那麼如何有效地保存這種關係(使用較少的代碼行,純粹用雄辯的ORM)是否可以在一行中保存一對多關係Laravel雄辯

這是問題的模型

class Question extends Model 
{ 
    protected $fillable = ['name' ,'type']; 

    public $timestamps = true; 

    public function answers(){ 

     return $this->hasMany('App\Answer'); 
    } 
} 

這是回答模式

class Answer extends Model 
{ 
    protected $fillable = ['answer']; 

    public $timestamps = true; 


    public function question(){ 

     return $this->belongsTo('App\Question'); 
    } 
} 
+0

我不明白什麼是問題,順便說一句,函數的答案應該重命名爲複數答案。 – Troyer

+0

謝謝答覆重新命名爲答案。 –

+0

@RehmanAkbar你能更具體地瞭解你需要什麼 – chanafdo

回答

1

在添加答案之前,您需要先提問。

<?php 

// Create both question and answer in one go. 
Question::create(['name' => 'Who is my father?']) 
    ->answers() 
    ->create(['answer' => 'Darth Vader']); 

// If you already have a question and want to add a new answer. 
$lukesQuestion->answers()->create(['answer' => 'Darth Vader']); 

請參閱有關Eloquent relations的文檔。

0

這就是Eloquent ORM的工作方式。如果你想利用雄辯,你無法避免這些關係功能。

如果您願意,您不必定義這些方法,但是您不能使用Eloquent的關係功能。

最後,這些語句需要的代碼大小與語言而不是框架有關。