簡體   English   中英

有可能在一對一行中雄辯地保存一對多關系嗎

[英]Is it possible to save one to many relation in one line Laravel eloquent

如何使用Laravel Eloquent在一行中保存此問題答案關系模型。 如果這不可能,那么如何有效地保存此關系(使用更少的代碼行,完全使用Eloquent ORM。)

這是問題模型

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');
    }
}  

在添加答案之前,您需要先提出一個問題。

<?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']);

請參閱有關雄辯關系的文檔。

這是雄辯的ORM的工作方式。 如果您想利用口才,就無法避免這些關系功能。

如果需要,您不必定義這些方法,但是您就不能使用Eloquent的關系功能。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM