私はLaravelには比較的新しいので、私は雄弁を使ってフォーラムを作ろうとしています。Laravel belongsTo外部キーが動作しない
私はメイクを使用:ユーザーの移行を行うには、authコマンドをとMySQL Workbenchおよび移行にERDを変換するためのプラグインを使用して、スレッドの移行を作成しました。その後
Schema::create($this->set_schema_table, function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('title', 45)->nullable();
$table->text('description')->nullable();
$table->timestamp('created_at')->nullable()->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->nullable()->default(DB::raw('CURRENT_TIMESTAMP'));
$table->unsignedInteger('created_by');
$table->index(["created_by"], 'fk_threads_users1_idx');
$table->foreign('created_by', 'fk_threads_users1_idx')
->references('id')->on('users')
->onDelete('no action')
->onUpdate('no action');
});
私は、スレッドのためのモデルを作成しました二つの間の関係を指定するユーザモデルを拡張:
class Thread extends Model
{
// No fields are protected in the database
protected $guarded = [];
public function user(){
return $this->belongsTo(User::class, 'created_by');
}
}
と
class User extends Authenticatable
{
public function threads(){
return $this->hasMany(Thread::class);
}
public function publish(Thread $thread){
$this->threads()->save($thread);
}
}
まず、この時
がうまく働いたが、何とかphp artisan cache:clear
実行した後(または多分何か他のものは、コードが動作を停止することがありましたが、私はわからない)スレッド制御部に格納方法は私にエラーを与えた:
Column not found: 1054 Unknown column 'user_id' in 'field list'
(SQL: insert into `threads` (`title`, `content`, `user_id`, `updated_at`, `created_at`)
values (Thread 4, content, 17, 2017-11-23 11:16:24, 2017-11-23 11:16:24))`
Threadクラスのuserメソッドで外部キーを "created_by"に指定している間に、フィールド "user_id"を見つけようとしています。
私はすべてが最初はうまくいきました。 これを修正する方法を知っている人はいますか?
はそれを片付けてくれてありがとう! – Joas
問題ありません!それがあなたを助けるのを見てよかった! – Laerte