2017-04-18 62 views
0

我試圖實現'有一個'關係,但是這個錯誤阻止我保存令牌。Laravel - SQLSTATE [42S22] - 外鍵

遷移:

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

錯誤:

照亮\數據庫\ QueryException與消息 'SQLSTATE [42S22]: 列未找到:1054未知列 '' 在' USER_ID字段列表'(SQL: 插入到usersemailiduser_idupdated_atcreated_at)值(電子郵件,1,1,2017年4月18日10時05分47秒,2017年4月18日10時05分47秒 ))」

回答

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

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

希望這對你的工作!

+0

其實,這就是我剛剛做的,他要求在用戶表中的'user_id'...我無法得到它。 ty幫助btw。 – Pixeuh

0

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

您是否嘗試過以下方法?

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

http://stackoverflow.com/questions/43472087/laravel-save-with-hasone-relation – Pixeuh

+0

刪除了問題或錯誤的鏈接 – aaron0207

相關問題