繁体   English   中英

Laravel属于外键不起作用

[英]Laravel belongsTo foreignkey not working

我是Laravel的新手,我正在尝试使用雄辩的方式建立一个论坛。

我使用make:auth命令进行了用户迁移,并使用mysql工作台和插件将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类的用户方法中指定外键应为“ created_by”时,它正在尝试查找“ user_id”字段。

我很确定起初一切都很好。 有谁知道如何解决这一问题?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM