Столбец не найден: 1054 неизвестных столбца ‘votables.question_id’ в ‘списке полей’

#mysql #laravel

#mysql #laravel

Вопрос:

Привет, ребята, я застрял с проблемой с 1 курсом. Это ошибка, которую я получаю :

 IlluminateDatabaseQueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'votables.question_id' in 'field list' (SQL: select `users`.*, `votables`.`question_id` as `pivot_question_id`, `votables`.`votable_id` as `pivot_votable_id`, `votables`.`votable_type` as `pivot_votable_type` from `users` inner join `votables` on `users`.`id` = `votables`.`votable_id` where `votables`.`question_id` in (2) and `votables`.`votable_type` = AppModelsUser)
 

Я создал полиморфные отношения из модели пользователя, модели вопросов и модели ответов в таблицу «votables»

 **User DB migration:**
Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
 

Вопрос миграции БД:

 Schema::create('questions', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('slug')->unique();
            $table->text('body');
            $table->unsignedInteger('views')->default(0);
            $table->unsignedInteger('answers')->default(0);
            $table->integer('votes_count')->default(0);
            $table->unsignedInteger('best_answer_id')->nullable();
            $table->unsignedBigInteger('user_id');
            $table->timestamps();

            $table->foreign('user_id')
                    ->references('id')
                    ->on('users')
                    ->onDelete('cascade');
        });
 

и миграция базы данных Votables:

 Schema::create('votables', function (Blueprint $table) {
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('votable_id');
            $table->string('votable_type');
            $table->tinyInteger('vote')->comment('-1: down vote, 1: up vote');
            $table->timestamps();
            $table->unique(['user_id', 'votable_id', 'votable_type']);
        });
 

Мой маршрут:

 Route::post('/questions/{question}/vote', VoteQuestionController::class);
 

VoteQuestionController :

 public function __invoke(Question $question){
        $vote = (int) request()->vote;
        auth()->user()->voteQuestion($question, $vote);

        return back();
    }
 

и модели — Пользователь

 public function voteQuestions(){
        return $this->morphedByMany(Question::class, 'votable');
    }

    public function voteAnswers(){
        return $this->morphedByMany(Answer::class, 'votable');
    }

    public function voteQuestion(Question $question, $vote){
        $voteQuestions = $this->voteQuestions();
        if($voteQuestions->where('votable_id', $question->id)->exists()){
            $voteQuestions->updateExistingPivot($question, ['vote' => $vote]);
        }
        else{
            $voteQuestions->attach($question, ['vote' => $vote]);
        }

        $question->load('votes');
        $downVotes = (int) $question->downVotes()->sum('vote');
        $upVotes = (int) $question->upVotes()->sum('vote');
        dd($upVotes);
        $question->votes_count = $upVotes   $downVotes;

        $question->save();
    }
 

и модель вопроса:

 public function votes(){
        return $this->morphedByMany(User::class, 'votable');
    }

    public function upVotes(){
        return $this->votes()->wherePivot('vote', 1);
    }

    public function downVotes(){
        return $this->votes()->wherePivot('vote', -1);
    }
 

Итак, после нажатия кнопки от пользователя auth для голосования по какому-либо вопросу я получаю в БД:

https://prnt.sc/wnbak9

Но в таблице вопросов они не учитывались, и я получаю эту ошибку после щелчка. Какие-то предложения?

Комментарии:

1. Вы упускаете связь (внешнюю) между голосами и вопросами

2. У вас есть сводные отношения, но нет сводной таблицы

3. votables — моя сводная таблица. В любом случае я нахожу ошибку, о которой идет речь, я сделал полиморфное отношение к пользователю с помощью morphedByMany , но должно быть morphToMany 🙂