【问题标题】:Relationship: category need article_id关系:分类需要article_id
【发布时间】:2020-01-12 23:45:21
【问题描述】:
我想创建关系one to many。所以我有带有"articlescategory_id" 列的表格文章。我也有桌子articlescategories。
我的人际关系是这样的
public function articles(){
return $this->hasMany('App\Article');
}
public function category(){
return $this->hasOne('App\Articlescategory');
}
它应该可以正常工作,但我有错误
"未找到列:1054 未知列
'articlescategories.article_id'”。列“articlescategory_id”分
关于类别
【问题讨论】:
标签:
php
mysql
laravel
relationship
【解决方案1】:
一对多反码是belongsTo 不是hasOne
主要区别:
belongsTo 和 belongsToMany 你是在告诉 Laravel 这个表包含连接到另一个表的外键
hasOne 和 hasMany 告诉 Laravel 这个表没有外键
更改您的代码:
public function category(){
return $this->belongsTo('App\Articlescategory');
}
【解决方案2】:
试试这个,直接将你的外键添加到你的关系船。并将hasOne 更改为belongsTo
public function category(){
return $this->belongsTo('App\Articlescategory', 'your_foreign_key_here');
}
例如
public function category(){
return $this->belongsTo('App\Articlescategory', 'articlescategory_id');
}