SQLSTATE[42S22]: Столбец не найден: 1054 Неизвестный столбец - Laravel


Я использую фреймворк Laravel.

У меня есть 2 таблицы (Пользователи и Участники). Когда я хочу войти в систему, я получаю сообщение об ошибке:

SQLSTATE[42S22]: Столбец не найден: 1054 Неизвестный столбец "user_email" в предложении "где" (SQL: выберите * из members где user_email =? предел 1) (Привязки: массив (0 =>'[email protected] ',))

Пользователи таблиц

CREATE TABLE IF NOT EXISTS `festival_aid`.`users` (
  `user_id` BIGINT NOT NULL AUTO_INCREMENT,
  `user_email` VARCHAR(45) NOT NULL,
  `user_created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `user_modified` TIMESTAMP NULL,
  `user_deleted` TIMESTAMP NULL,
  `user_lastlogin` TIMESTAMP NULL,
  `user_locked` TIMESTAMP NULL,
  PRIMARY KEY (`user_id`),
  UNIQUE INDEX `user_email_UNIQUE` (`user_email` ASC),
ENGINE = InnoDB;

Члены таблицы

CREATE TABLE IF NOT EXISTS `festival_aid`.`members` (
  `member_id` BIGINT NOT NULL AUTO_INCREMENT,
  `member_password` CHAR(32) NOT NULL,
  `member_salt` CHAR(22) NOT NULL,
  `member_token` VARCHAR(128) NULL,
  `member_confirmed` TIMESTAMP NULL,
  `user_id` BIGINT NOT NULL,
  PRIMARY KEY (`member_id`, `user_id`),
  INDEX `fk_members_users1_idx` (`user_id` ASC),
  CONSTRAINT `fk_members_users1`
    FOREIGN KEY (`user_id`)
    REFERENCES `festival_aid`.`users` (`user_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

Пользователь миграции

public function up()
    {
        Schema::table('users', function(Blueprint $table)
        {
            $table->increments('user_id');

            $table->string('user_email');
            $table->timestamp('user_created');
            $table->timestamp('user_modified');
            $table->timestamp('user_deleted');
            $table->timestamp('user_lastlogin');
            $table->timestamp('user_locked');
        });
    }

Миграция Участник

public function up()
    {
        Schema::table('members', function(Blueprint $table)
        {
            $table->increments('member_id');

            $table->string('member_password');
            $table->string('member_salt');
            $table->string('member_token');

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

            $table->timestamp('member_confirmed');
        });
    }

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

class User extends Eloquent {

    protected $table = 'users';

    /**
     * The primary key for the model.
     *
     * @var string
     */
    protected $primaryKey = 'user_id';

    public $timestamps = false;
}

Член модели

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;

class Member extends Eloquent implements UserInterface, RemindableInterface {

    protected $table = 'members';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('member_password');

    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getAuthIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword()
    {
        return $this->member_password;
    }

    /**
     * Get the e-mail address where password reminders are sent.
     *
     * @return string
     */
    public function getReminderEmail()
    {
        return $this->email;
    }

    /**
     * The primary key for the model.
     *
     * @var string
     */
    protected $primaryKey = 'member_id';

    public $timestamps = false;

    public function users()
    {
        return $this->hasOne('User');
    }
}

Модель участника использует: использовать интерфейс Illuminate\Auth\пользователя;

<?php namespace Illuminate\Auth;

interface UserInterface {

    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getAuthIdentifier();

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword();

}

Контроллер

public function store()
    {
        $input = Input::all();

        $rules = array('user_email' => 'required', 'member_password' => 'required');

        $v = Validator::make($input, $rules);

        if($v->passes())
        {
            $credentials = array('user_email' => $input['user_email'], 'member_password' => $input['member_password']);

            if(Auth::attempt($credentials))
            {
                return Redirect::to('/home');

            } else {

                return Redirect::to('login');
            }

        } else {

            return Redirect::to('login')->withErrors($v);
        }
    }

Auth.php

return array(

    /*
    |--------------------------------------------------------------------------
    | Default Authentication Driver
    |--------------------------------------------------------------------------
    |
    | This option controls the authentication driver that will be utilized.
    | This drivers manages the retrieval and authentication of the users
    | attempting to get access to protected areas of your application.
    |
    | Supported: "database", "eloquent"
    |
    */

    'driver' => 'eloquent',

    /*
    |--------------------------------------------------------------------------
    | Authentication Model
    |--------------------------------------------------------------------------
    |
    | When using the "Eloquent" authentication driver, we need to know which
    | Eloquent model should be used to retrieve your users. Of course, it
    | is often just the "User" model but you may use whatever you like.
    |
    */

    'model' => 'Member',

    /*
    |--------------------------------------------------------------------------
    | Authentication Table
    |--------------------------------------------------------------------------
    |
    | When using the "Database" authentication driver, we need to know which
    | table should be used to retrieve your users. We have chosen a basic
    | default value but you may easily change it to any table you like.
    |
    */

    'table' => 'members',

    /*
    |--------------------------------------------------------------------------
    | Password Reminder Settings
    |--------------------------------------------------------------------------
    |
    | Here you may set the settings for password reminders, including a view
    | that should be used as your password reminder e-mail. You will also
    | be able to set the name of the table that holds the reset tokens.
    |
    | The "expire" time is the number of minutes that the reminder should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'reminder' => array(

        'email' => 'emails.auth.reminder',

        'table' => 'password_reminders',

        'expire' => 60,

    ),

);

Что я здесь делаю не так?

Author: Gilko, 2013-12-21

3 answers

Вы настроили auth.php и использовали таблицу members для аутентификации, но в таблице members нет поля user_email, поэтому Ларавель говорит

SQLSTATE[42S22]: Столбец не найден: 1054 Неизвестный столбец "user_email" в предложении "где" (SQL: выберите * из членов, где user_email =? предел 1) (Привязки: массив (0 =>'[email protected] ',))

Потому что он пытается сопоставить user_email в таблице members, но его там нет. В соответствии с вашим auth конфигурация, laravel использует таблицу members для аутентификации, а не таблицу users.

 20
Author: The Alpha, 2013-12-20 22:28:02

У вас нет поля с именем user_email в таблице участников ... что касается того, почему, я не уверен, поскольку код "выглядит" так, как будто он должен пытаться присоединиться к разным полям

Выполняет ли метод Auth::попытка объединение схемы? Запустите grep -Rl 'class Auth' /path/to/framework и найдите, где находится метод attempt и что он делает.

 3
Author: Cez, 2013-12-20 21:08:54

Попробуйте изменить, где класс-член

public function users() {
    return $this->hasOne('User');
} 

return $this->belongsTo('User');
 -1
Author: bandzi, 2017-06-21 14:46:51