DBIx:具有附加属性的类多对多关系 [英] DBIx:Class many-to-many relationship with additional attribute
问题描述
我正在 Catalyst 框架中使用 DBIx::Class.我的本地目标是在用户和任务之间添加新的多对多关系.但是我需要一个小技巧.用户可以在任务中拥有不同的角色(例如工人"或旁观者").
I'm working with DBIx::Class in Catalyst framework. My local goal is to add a new many-to-many relationship between users and, let's say, tasks. But there's one little trick I need. User can have different roles in task (like 'worker' or 'spectator').
所以我有带有这些字段的用户表:
So I have users table with these fields:
- id
- 姓名
我有包含这些字段的任务表:
I have task table with these fields:
- id
- 标题
- 说明
而且我有包含以下字段的关系表 user_tasks:
And I have relationship table user_tasks with these fields:
- user_id
- task_id
- 角色
我已经设置了从users到user_tasks的has_many,从tasks到user_tasks的has_many以及相应的many_to_many关系用户和任务之间.那个简单的部分可以正常工作.
I have set up has_many from users to user_tasks, has_many from tasks to user_tasks and corresponding many_to_many relationships between users and tasks. And that plain part works as it should.
然后,例如,我想获取我的用户列表,包括用户在 $task_id 标识的任务中的角色:
Then, for example, I want to get my user list including user's role in task identified by $task_id:
my $users = $schema->resultset('User')->with_task_role($task_id);
while (my $u = $users->next) {
print "User: " . $u->name . ", role: " . $u->get_column('task_role');
}
那么我应该如何编码这个 with_task_role 自定义结果集以在我的查询中使用用户的任务角色获取这个附加字段?
So how should I code this with_task_role custom resultset to get this additional field with user's task role in my query?
推荐答案
首先,多对多不是一种关系.它是一个访问器(关系桥梁).
First of all many-to-many is not a relationship. It's a accessor (a relationship bridge).
其次,DBIx::Class 有一个很好的文档.看看加入/预取.在您的 ResultSet/User.pm 文件中,您应该有如下内容:
Second, the DBIx::Class has an excellent documentation. Take a look at join/prefetch. In your ResultSet/User.pm file you should have something like:
sub with_task_role {
my ($self, $task_id) = @_;
return $self->search({
'task.task_id' => $task_id,
},
{
join => { 'user_task' => 'task' },
prefetch => { 'user_task' => 'task' },
},
);
}
PS:抱歉,我没看到 Ashley 已经回答了PS2:最后一行})"之前应该只有)"(已修复)
PS: Sorry, I didn't see that Ashley already answered PS2: Before the last line "})" should be ")" only (fixed it)
这篇关于DBIx:具有附加属性的类多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!