сохранение кратных внешних ключей в laravel - PullRequest
0 голосов
/ 06 августа 2020

Вот моя ситуация:

В моем контроллере мне нужно сохранить два внешних ключа: exam_id и category_id, но всегда говорю:

SQLSTATE[HY000]: General error: 1364 Field 'exam_id' doesn't have a default value

Контекст: у экзамена есть вопросы (у экзамена много вопросов, но вопрос принадлежит экзамену). Также Вопрос относится к категории, а Категория имеет много вопросов. В модели выглядит как

Category

class Category extends Model{
    protected $fillable = [
        'name'
    ];
    
    public function questions(){
        return $this->hasMany(Question::class);
    }
}

Exam

class Exam extends Model{
    protected $fillable = [
        'user_id', 'title', 'description', 'score'
    ];
    protected $guarded = [];
    
    public function user(){
        return $this->belongsTo(User::class);
    }

    public function questions(){
        return $this->hasMany(Question::class);
    }
}

Question

class Question extends Model{
     protected $fillable = [
         'exam_id', 'category_id' ,'description', 'iframe', 'image',
     ];

     protected $guarded = [];

     public function exam(){
         return $this->belongsTo(Exam::class, 'exam_id');
     }

     public function category(){
         return $this->belongsTo(Category::class);
     }
}

QuestionController

public function store(QuestionStoreRequest $request){
        $questions = Question::create($request->all());
        $questions->exam()->attach($request->get('exam_id'));
        $questions->category()->attach($request->get('category_id'));

        $questions->save();

        return view('question.create');
    }

Когда я пытаюсь сэкономить на моем методе магазина, никогда не вставляйте поле exam_id и idk, почему? Как сохранить кратный внешний ключ?

ОБНОВЛЕНИЕ 1:

Я добавляю, как объявлять мои таблицы (и отношения)

+----+---------+----------------+--------------------------------+-------+---------------------+---------------------+
| id | user_id | title          | description                    | score | created_at          | updated_at          |
+----+---------+----------------+--------------------------------+-------+---------------------+---------------------+
|  1 |       1 | Primer examen  | Examen de testing              |   100 | 2020-07-31 05:26:31 | 2020-07-31 05:26:31 |
|  4 |       1 | Segundo examen | Descripcion del segundo examen |   100 | 2020-08-04 21:10:18 | 2020-08-04 21:10:18 |
+----+---------+----------------+--------------------------------+-------+---------------------+---------------------+

 select * from questions;
+----+---------+-------------+-------------------------------+----------------------+-------+-------+---------------------+---------------------+
| id | exam_id | category_id | description                   | iframe               | image | order | created_at          | updated_at          |
+----+---------+-------------+-------------------------------+----------------------+-------+-------+---------------------+---------------------+
|  1 |       1 |           1 | ¿Capital de mexico?           | algo nomas de prueba | NULL  |  NULL | 2020-08-06 06:45:50 | 2020-08-06 06:45:50 |
|  2 |       1 |           2 | ¿Capital de Rusia?            | algo nomas de prueba | NULL  |  NULL | 2020-08-06 06:54:39 | 2020-08-06 06:54:39 |
|  3 |       4 |           1 | ¿Hoy es viernes, loremp ipsu? | algo nomas de prueba | NULL  |  NULL | 2020-08-06 06:58:18 | 2020-08-06 06:58:18 |
+----+---------+-------------+-------------------------------+----------------------+-------+-------+---------------------+---------------------+

И когда я вставляю вопрос, вставьте вопрос, введите exc_id.

Я пытаюсь сделать следующее: когда я вставляю вопрос, он должен взять идентификатор экзамена, которому он принадлежит. Я не знаю, следует ли это сохранять в контроллере вопросов или в контроллере экзамена.

ОБНОВЛЕНИЕ 3:

вывод dd ():

array:4 [▼
  "_token" => "ec4qvPN6hySporQUvZrnAIqkmZEOCvAMLFAUQB6q"
  "description" => "igdiysagdfyud"
  "iframe" => "iysgdfygsdyufgsdf"
  "category" => "3"
]

ОБНОВЛЕНИЕ 4

Форма вопроса (получить category_id)

<form action="/questions" method="POST" enctype="multipart/form-data">
    @CSRF
    <div class="form-group">
        <label for="description">Descripcion de la pregunta*</label>
        <textarea name="description" type="text"
                  class="form-control" id="description"
                  aria-describedby="descriptionHelp"
                  placeholder="Inserte la pregunta">{{ old('description') }}</textarea>
        <small id="descriptionHelp"
               class="form-text text-muted">Escribe la descripcion de la pregunta.</small>
    </div>
    <div class="form-group">
        <label for="iframe">Video asociado *</label>
        <textarea name="iframe" type="text"
                  class="form-control" id="iframe"
                  aria-describedby="iframeHelp"
                  placeholder="Inserte la URL del video">{{ old('iframe') }}</textarea>
        <small id="iframeHelp" class="form-text text-muted">Inserta la url del video.</small>
    </div>

    <div class="form-group d-flex flex-column">
        <label for="image">Imagen asociada</label>
        <input name="image" type="file" class="py-1">
    </div>
    <div class="form-group">
        <label for="category">A que categoria pertenece</label>
        <select name="category" class="form-control form-control-lg" id="category">
            @foreach($category as $category)
                <option value="{{ $category->id }}">{{ $category->name }}</option>
            @endforeach
        </select>
        <small id="selectHelp" class="form-text text-muted">Elige una categoria.</small>
    </div>
    <hr />
    <button type="submit" class="btn btn-primary">Guardar pregunta</button>
</form>

1 Ответ

1 голос
/ 06 августа 2020

почему бы не использовать прямые свойства?

public function store(QuestionStoreRequest $request){
        $questions =new  Question();
        $questions->description=$request->get('description');
        $questions->iframe=$request->get('iframe');
        $questions->image=$request->get('image');
        $questions->exam_id=$request->get('exam_id');
        $questions->category_id=$request->get('category_id');
        $questions->save();
        return view('question.create');
    }

таким образом, вы go сделаете db один раз, а не три раза

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...