代码之家  ›  专栏  ›  技术社区  ›  vishwas jadav

在laravel中获取具有雄辩关系的错误列数据

  •  2
  • vishwas jadav  · 技术社区  · 8 年前

    我有两个国家和州的模型。 它们之间的关系如下所示: 国家/地区:

    public function States()
    {
       return $this->hasMany('App\State');
    }
    

    国家:

    public function Country()
    {
      return $this->belongsTo('App\Country');
    }
    

    现在,我想在show方法中获取属于国家的状态。

    public function show(Country $country)
    {
        $states = $country->States()->get();
        dd($states);
    }
    

    但是,这里它抛出了一个错误: SQLSTATE[42S22]:未找到列:1054未知列的状态。“where子句”中的country\u id“(SQL:选择*自 states 哪里 各州 . country_id =11和 各州 . country\u id 不为空)

    country\u id不存在是正确的,因为它被命名为countries\u id 因为国家表的名称是国家。

    请帮助解决此错误。

    2 回复  |  直到 8 年前
        1
  •  2
  •   Sohel0415    8 年前

    你的 foreign key 不匹配,将外键列添加为 second 上的参数 relationship 作用

    public function States()
    {
      return $this->hasMany('App\State','countries_id');
    }
    

    通过 convention ,雄辩地 "snake case" 拥有模型的名称和 suffix 它与 _id 外键 . 这就是为什么 country_id 而不是 countries_id .

        2
  •  1
  •   Alexey Mezenin    8 年前

    向关系定义添加外键:

    return $this->hasMany('App\State', 'countries_id');
    

    https://laravel.com/docs/5.5/eloquent-relationships#one-to-many