Почему laravel push выдает ошибку 1364: поле 'question_entity_id' не имеет значения по умолчанию? - PullRequest
1 голос
/ 09 июля 2019

Я очень новичок в Laravel (это мой первый раз, когда я его использую), и я пытаюсь сохранить некоторые данные, которые я сделал в пост-запросе к моему API. Я продолжаю получать общую ошибку: 1364 Поле 'question_entity_id' не имеет значения по умолчанию.

Я пытаюсь использовать метод push Laravel для сохранения модели 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');
        });

1 Ответ

0 голосов
/ 10 июля 2019

Добавьте question_entity_id в вашу ItemBank модель, вот так.

protected $fillable = [
    'question_entity_id',
];

Итак, ваша ItemBank модель будет выглядеть следующим образом.

class ItemBank extends Model
{
    // table name
    protected $table = "item_bank";
    protected $fillable = [
    'question_entity_id','correct_answers'
];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...