在Laravel和Sqlite中跨数据库多对多关系



在Laravel框架8.20.1中,我有两个模型,User和Item,在两个不同的SQLITE数据库中,具有多对多关系。

与模型Item在同一数据库中的中间表item_user。

我已经在模型Item

中设置了belongsToMany关系
class Item extends Model
{
...

protected $connection = 'connection2-name';
public function users()
{
return $this->belongsToMany(User::class);
// I have done several tryouts
//  OR  return $this->belongsToMany(User::class, 'item_user', 'user_id', 'item_id');
//  OR  return $this->belongsToMany(User::class, 'sqlite-db2.item_user', 'user_id', 'item_id');
//  OR  return $this->belongsToMany(User::class, '/path/to/sqlite-db2.item_user', 'user_id', 'item_id');
//  OR  return $this->belongsToMany(User::class, 'connection2-name.item_user', 'user_id', 'item_id');
}
}

当我试图访问项目与用户:

$item = Item::find($id)->with('users')->get();

我得到一个错误,我的中间表"item_user"不存在。

一般错误:1 no such table: item_user

就我在搜索解决方案时发现的问题而言,问题应该是Laravel假设中间表存在于与目标关系相同的数据库中,因此他们建议在belongsToMany中添加db名称,但即使这样也没有解决我的问题。

你有什么提示可以解决这个问题吗?

首先,您需要创建一个包含字段user_id and item_id的表item_users

然后使用relation:

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

最新更新