如何在Laravel中自动填充多对一关系中的外键ID?

How to auto fill foreign key id in many-to-one relationship in Laravel?

我有两个型号 QuestionFactor。一个 Factor 属于多个 Question,每个 Question 有一个 Factor。我在 models.I 中定义了这种多对一关系,想在 QuestionController 中存储一个因子。我找到问题对象并通过该对象创建一个因子 question.When 我在 Postman,因素成功存储,但factor_id 不自动插入问题 table.I 不想通过因素创建问题对象(这种方式的逆转)。因为因子对象是在支付完成时创建的,并且在问题对象 created.How 之前创建? 这是问题 table:

 Schema::create('questions', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title')->nullable();
        $table->timestamps();
        $table->integer('factor_id')->unsigned()->nullable();
        $table->foreign('factor_id')->references('factors')->on('id')->onDelete('cascade');
    });

这是因素 table:

 Schema::create('factors', function (Blueprint $table) {
        $table->increments('id');
        $table->string('number_factor')->nullable();
        $table->decimal('total_price',15,2)->nullable();
        $table->timestamps();
    });

这是问题模型:

  class Question extends Model
{
    protected $guarded=[];
    public function factors()
    {
        return $this->belongsTo(Factor::class,'factor_id');
    }
}

这是因子模型:

 class Factor extends Model
{
    protected $guarded=[];
    public function questions()
    {
        return $this->hasMany(Question::class,'factor_id');
    }
}

这是QuestionController:

 public function storeFactor(Request $request,$questionId)
{
    $question=Question::find($questionId);
    if(is_null($question)){
        return response()->json([
            'success'=>false,
            'message'=>'This question is not exist!'
        ],404);
    }
    $question->factors()->create($request->all());
    $question->save();
    return response()->json([
        'success'=>true,
        'message'=>'Factor successfully Stored.'
    ],200);
}

这是我的路线:

Route::post('question/storeFactor/{id}','API\QuestionController@storeFactor');

您可以在已创建的模型实例上使用 save() 关系方法。

先创建因子,再保存题目。例如$factor->questions()->save($question);