Laravel belongsTo 外键无效

Laravel belongsTo foreignkey not working

我对 Laravel 比较陌生,我正在尝试使用 eloquent 创建一个论坛。

我使用 make: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))`

如您所见,它正在尝试查找字段 "user_id",而我在线程 class.[=16= 的用户方法中指定外键应为 "created_by" ]

我很确定一开始一切正常。 有谁知道如何解决这个问题?

您应该将 hasMany 方法修改为:

return $this->hasMany('App\Comment', 'foreign_key');

参考:https://laravel.com/docs/5.5/eloquent-relationships

将代码更改为:

public function threads(){
    return $this->hasMany(Thread::class, 'created_by');
}