Laravel - SQLSTATE [42S22] - 外键

时间:2017-04-18 09:09:05

标签: sql laravel pdo

我正在尝试实现'has one'关系,但是这个错误阻止我保存令牌。

迁移:

class CreatePasswordTokensTable extends Migration
{
    public function up()
    {
        Schema::create('password_tokens', function (Blueprint $table) {
            $table->engine = 'InnoDB';

            $table->increments('id');
            $table->integer('user_id')->unsigned()->index();
            $table->foreign('user_id')->references('id')->on('users');
            $table->string('token');

        });
    }

    ...
}

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->engine = 'InnoDB';

            $table->increments('id');
            $table->string('email')->unique();
            $table->string('password')->default('');
            $table->string('remember_token', 100)->default('');
            $table->boolean('active')->default(false);
            $table->timestamps();
        });
    }

    ...
}

模特:

class User extends Model
{
    public function passwordToken()
    {
        return $this->hasOne('App\Models\PasswordToken');
    }
}

class PasswordToken extends Model
{
    public function user() {
        return $this->belongsTo('App\Models\User');
    }
}

命令 - enter image description here

在保存调用后显示奇怪的user_id - enter image description here

错误:

  

Illuminate \ Database \ QueryException,消息为'SQLSTATE [42S22]:   未找到列:1054'字段列表'中的未知列'user_id'(SQL:   插入usersemailiduser_idupdated_at,   created_at)值(电子邮件,1,1,2017-04-18 10:05:47,2017-04-18   10时05分47秒))'

3 个答案:

答案 0 :(得分:0)

如果您使用的是Laravel 5.3请尝试:

Schema::create('password_tokens', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->unsignedInt('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->string('token');

        });

答案 1 :(得分:0)

我认为您可以像这样更新您的模型:

class User extends Model
{

   public function passwordToken(){
       return $this->hasOne('App\Models\PasswordToken','user_id', 'id');
   }

}

class PasswordToken extends Model
{

   public function user()
   {
       return $this->belongsTO('App\Models\User', 'user_id', 'id');
   }
}

希望这对你有用!

答案 2 :(得分:0)

您是否在模型中填写$ table和$ fillable属性?

您是否尝试过以下操作?

$user->save();
$token->user_id = $user->id;
$token->save();