【发布时间】:2019-07-10 08:35:45
【问题描述】:
我对 Laravel 非常陌生(这是我第一次使用它),我正在尝试将一些数据存储在我的 api 的发布请求中。我不断收到一般错误:1364 字段“question_entity_id”没有默认值。
我正在尝试使用 Laravel 的 push 方法来保存 itemBank 模型以及我在下面定义的所有关系,但我得到了上面的错误。我已经尝试手动设置 foreign_key 关系,例如 `$itemBank->question_entity_id = $questionEntity->id' 但这给了我同样的错误。我特别想弄清楚为什么 question_entity_id 没有被填充(我知道可以通过使该字段为空或给 question_entity_id 一个默认值来解决该错误)。
以下是相关模型:
class ItemBank extends Model
{
// table name
protected $table = "item_bank";
// do no use default timestamp fields
public $timestamps = false;
// item_bank relationships to other Models/tables
public function questionEntity() {
return $this->hasOne('App\QuestionEntity', 'id', 'question_entity_id');
}
public function optionEntity() {
return $this->hasMany('App\OptionEntity', 'item_id', 'id');
}
public function tagItemRel() {
return $this->hasOne('App\TagItemRel', 'item_id', 'id');
}
}
class QuestionEntity extends Model
{
// table name
protected $table = 'question_entity';
// disable default timestamps
public $timestamps = false;
public function itemBank() {
return $this->belongsTo('App\ItemBank', 'id', 'question_entity_id');
}
}
这是我尝试存储数据的代码:
public function store(Request $request)
{
$data = $request->all();
$itemBank = new ItemBank();
//save question body text
$questionEntity = new QuestionEntity();
$questionEntity->question = $data['questionBody'];
$itemBank->questionEntity()->save($questionEntity);
// save correct answer
$itemBank->correct_answers = $data['correctAnswer'];
//save question options
$choices = ['A', 'B', 'C', 'D'];
//$optionEntities = [];
foreach($choices as $choice) {
$optionEntity = new OptionEntity();
$optionEntity->choice = $data['choice' . $choice];
$optionEntity->choice_label = $choice;
$optionEntity->itemBank()->associate($itemBank);
}
//$itemBank->optionEntity()->saveMany($optionEntities);
//create new ItemTag Model
$itemTag = new ItemTag();
$itemTag->tag_name = $data['topic'];
//create new TagItemRel Model
$tagItemRel = new TagItemRel();
$tagItemRel->itemTag()->save($itemTag);
$tagItemRel->itemBank()->associate($itemBank);
$itemBank->push();
return $itemBank;
}
以下是相关的迁移文件:
QuestionEntity:
Schema::create('question_entity', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('question', 500);
});
ItemBank:
Schema::create('item_bank', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('question_entity_id');
$table->string('correct_answers', 1);
$table->foreign('question_entity_id')->references('id')->on('question_entity');
});
【问题讨论】:
-
嗨库马洛。您的错误消息很清楚:您的表“item_bank”中有一个字段
question_entity_id,它不能为空,也没有默认值。您的代码不会填写此字段,但无论如何都会尝试保存记录。这会导致此错误。要修复它,要么使字段为空(如果它有意义)或为表中的字段定义默认值,或者确保您的代码使用正确的 id 填充字段。也许您可以显示表定义?这将极大地帮助我们提供建议。 -
@RobBiermann 抱歉,我的问题应该更清楚。我试图弄清楚为什么我的代码没有用正确的 id 填充代码。我已添加您要求的定义。
-
非常重要:您的关系定义中有错误的键。
return $this->hasOne('App\QuestionEntity', 'id', 'question_entity_id');必须是return $this->hasOne('App\QuestionEntity', 'question_entity_id', 'id');
标签: php laravel-5 post eloquent