【问题标题】: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');
    }
    

    【讨论】:

      猜你喜欢
      • 2013-11-27
      • 1970-01-01
      • 2021-06-14
      • 2016-09-17
      • 2011-06-12
      • 2019-03-04
      • 2015-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多