交叉数据库与Sqlite在Laravel中的许多关系到许多关系
在Laravel Framework 8.20.1中,我在两个不同的SQLITE数据库中有两个模型,用户和项目,具有许多与许多关系。
中间表,称为item_user,在与模型项目同一数据库中。
我已经在模型项目中设置了类似的属于属性的relatinoship
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没有这样的表:item_user
一般错误:1没有这样的表:就我在搜索解决方案时发现的 ,问题应该是Laravel假设中间表与目标关系相同的数据库中存在,因此他们建议添加DB在《属于属于的人》中的名字,但即使不是解决我的问题。
您是否有任何提示可以解决这个问题?
In Laravel Framework 8.20.1 I have two models, User and Item, in two different SQLITE databases, with a many to many relationship.
The intermediate table, called item_user, in the same database as model Item.
I've setup the belongsToMany relatinoship like this in model Item
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');
}
}
When I try to access Item with Users:
$item = Item::find($id)->with('users')->get();
I get an error that my intermediate table "item_user" doesn't exist.
General error: 1 no such table: item_user
As far as I have found in my search of the solution, the problem should be that Laravel assumes the intermediate table to exist in the same database as the target relation, so they suggest to add the db name in the belongsToMany, but even that did not solve my issue.
Do you have any hint to come out of this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您需要使用字段 user_id and item_id 创建表
item_user
然后使用关系:
First of all you need to create a table
item_users
with fieldsuser_id and item_id
Then use relation: