![](/img/trans.png)
[英]How to get one->many relationship with a foreign key in laravel 5.2?
[英]How to auto fill foreign key id in many-to-one relationship in Laravel?
我有兩個模型叫做Question
和Factor
。 一個Factor
屬於許多Question
,每個Question
都有一個Factor
。 我在模型中定義了這種多對一關系。我想將一個因素存儲在QuestionController
。我找到問題對象並通過該問題創建一個因素。當我在Postman
測試此函數時,該因素已成功存儲,但是factor_id
don不會自動插入問題表。我不想通過一個因素來創建問題對象(這種方式是相反的)。 因為因子對象是在付款時和問題對象創建之前創建的,該怎么辦? 這是問題表:
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');
});
這是因子表:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.