【问题标题】:Laravel - SQLSTATE[42S22] - Foreign keyLaravel - SQLSTATE [42S22] - 外键
【发布时间】:2017-09-14 01:09:36
【问题描述】:

我正在尝试实现“有一个”关系,但此错误阻止我保存令牌。

迁移:

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');
    }
}

命令 -

保存调用后出现奇怪的 user_id -

错误:

Illuminate\Database\QueryException 并带有消息“SQLSTATE[42S22]: 未找到列:1054“字段列表”中的未知列“user_id”(SQL: 插入users (email, id, user_id, updated_at, created_at) 值 (email, 1, 1, 2017-04-18 10:05:47, 2017-04-18 10:05:47))'

【问题讨论】:

    标签: sql laravel pdo


    【解决方案1】:

    如果你使用 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');
    
            });
    

    【讨论】:

      【解决方案2】:

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

      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');
         }
      }
      

      希望这对你有用!

      【讨论】:

      • 其实,这就是我刚刚所做的,他在用户表中要求一个'user_id'......我无法得到它。顺便说一句,请帮忙。
      【解决方案3】:

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

      您是否尝试过以下操作?

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

      【讨论】:

        猜你喜欢
        • 2020-10-02
        • 2015-08-10
        • 2018-10-20
        • 1970-01-01
        • 2020-07-26
        • 2018-02-21
        • 2015-12-08
        • 2018-11-02
        相关资源
        最近更新 更多