php - Laravel hasMany 和 belongsToMany 关系
问题描述
我一直在与我的 Laravel 关系作斗争。
所以我有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.phpcountries
user_id
countries
user_id
我知道问题是它在国家而不是国家用户中寻找。如何定义我想在哪里搜索关系?
这是我的用户模型
public function countries()
{
return $this->hasMany('App\Models\Countries');
}
还有我的国家模型
public function users()
{
return $this->belongsToMany(User::class);
}
解决方案
尝试指定表名
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';
//...
}
推荐阅读
- android - Firebase 身份验证:在身份验证期间没有收到来自 FirebaseUser 的电子邮件
- html - 从 Vue 调用 laravel 路由
- c# - 如何按部分将 JSON 文件反序列化为 C# 对象
- php - 按钮和表格下拉列表显示 Laravel 8 中的重复值
- kubernetes-helm - helm 语法 {{ something }} 和 {{- something }} 有什么区别?
- sql - 雪花 Where 子句没有过滤?
- java - 为什么这段代码说 x 没有初始化,但是当我们在 if 语句中执行 print 语句时它工作正常?
- javascript - 将对象作为道具传递
- python - 如何使用python从网站中提取所有链接
- discord - 用于将用户添加到频道的 Discord Reaction OR 命令