首页 > 解决方案 > Laravel hasMany 和 belongsToMany 关系

问题描述

我一直在与我的 Laravel 关系作斗争。

所以我有3张桌子:

  1. 用户
  2. 国家
  3. 国家用户

如您所见,关系是国家用户。现在每次都会出现如下错误:

Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'countries.user_id' in 'where clause' (SQL: select

  • 从哪里来。countries_ = 1 和. 不为空)在第 671 行的文件 C:\xampp\htdocs\gManager\vendor\laravel\framework\src\Illuminate\Database\Connection.phpcountriesuser_idcountriesuser_id

我知道问题是它在国家而不是国家用户中寻找。如何定义我想在哪里搜索关系?

这是我的用户模型

public function countries()
    {
        return $this->hasMany('App\Models\Countries');
    }

还有我的国家模型

public function users()
    {
        return $this->belongsToMany(User::class);
    }

标签: phpmysqllaravel

解决方案


尝试指定表名

public function users()
{
    return $this->belongsToMany(User::class, 'countries_user');
}

并且反向关系也应该是belongsToMany

public function countries()
{
    return $this->belongsToMany(Countries::class, 'countries_user');
}

并在国家模型上指定表属性

class Countries extends Model
{
    protected $table = 'countries';

    //...
}

推荐阅读