[英]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.