简体   繁体   English

Laravel hasMany和belongsToMany关系

[英]Laravel hasMany and belongsToMany relationship

I have struggled with my Laravel relationships.我一直在努力处理我的 Laravel 关系。

So I have 3 tables:所以我有3张桌子:

  1. Users用户
  2. Countries国家
  3. countries_user国家用户

As you can see relation is countries_user.如您所见,关系是国家用户。 Now every time gives error like:现在每次都会出现如下错误:

Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'countries.user_id' in 'where clause' (SQL: select Illuminate\Database\QueryException:SQLSTATE [42S22]:找不到列:1054 'where 子句'中的未知列'countries.user_id'(SQL:select

  • from countries where countries .来自countriescountries user_id = 1 and countries . user_id = 1 和countries user_id is not null) in file C:\xampp\htdocs\gManager\vendor\laravel\framework\src\Illuminate\Database\Connection.php on line 671 user_id不为空)在文件 C:\xampp\htdocs\gManager\vendor\laravel\framework\src\Illuminate\Database\Connection.php 行 671

I understand the problem is that it's looking in countries and not in countries_user.我知道问题是它在国家而不是国家用户中寻找。 How to define where I want to search the relation?如何定义我想在哪里搜索关系?

Here is my User model这是我的用户 model

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

And my Countries Model还有我的国家 Model

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

Try specifying the table name尝试指定表名

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

And the inverse relation should also be belongsToMany并且反向关系也应该是belongsToMany

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

And also specify the table property on Countries model并在国家 model 上指定表属性

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

    //...
}

The countries relationship should be belongsToMany too. countries关系也应该是belongsToMany
Instead of代替

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

put

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM