Laravel属于外键不工作

时间:2017-11-23 11:43:32

标签: php laravel eloquent laravel-5.5

我对Laravel来说相对较新,我正试图用口才创建一个论坛。

我使用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之后(或者其他可能导致代码停止工作的东西,我不确定)线程控制器中的store方法给了我一个错误:< / p>

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))`

正如您所看到的,它正在尝试找到字段&#34; user_id&#34;而我指定的外键应该是&#34; created_by&#34;在Thread类的用户方法中。

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

1 个答案:

答案 0 :(得分:0)

您应该修复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');
}