- Rails是“常规配置”。模型”必须为单数“人物”。
$this->people()->attach($person['id'], ['role' => $role]);
Laravel代码片段的说明
People
是与通过$this
类通过Role
访问的类的多态关联。上面的函数在中间表(角色/人员)中创建一条记录,如下所示:id: {{generically defined}}
people_id: $person['id']
role: $role
peopleable_type: $this->type
peopleable_id: $this->id
如何在Laravel端定义关联:
class XYZ {
...
public function people()
{
return $this->morphToMany(People::class, 'peopleable')->withPivot('role','id');
}
...
}
这是我在Ruby中建立关联的方式:我在Ruby中的努力
class Peopleable < ApplicationRecord
belongs_to :people
belongs_to :peopleable, polymorphic: true
end
class People < ApplicationRecord
has_many :peopleables
end
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
我已经看到了操作<<
,但我不知道在触发此操作时是否有任何方法可以在数据透视表上设置其他值。 [在这种情况下,roles
或peopleables
表;我在此应用程序中可以互换使用这两个术语。]
PS。因此,基本上的问题是,如何在ActiveRecord中的多态多关联中在数据透视表上定义其他值,并在启动附件关系时动态设置这些值]
功能说明
这些内容类型中的每一个都可以与扮演某些角色的个人相关联:编辑,作者,翻译等。>
因此,例如:
X是Post#1的翻译器。 X,Y和Z是帖子#1的作者。的概念是指[[有一个不同的
People
模型,每种内容类型都有自己的唯一模型[例如:Post
,Poem
等]。:through
Role
类”或“数据透视表”(无论您希望了解哪种方式,都在其上记录了多态关联。)>除了有关简单多态关系的信息外,数据透视表上还记录了这种角色。例如,X既是Post#1的作者又是翻译者,因此有两行具有相同的people_id
,peopleable_type
和peopleable_id
,但是对于role
它们具有不同的值。
我正在从“ Laravel ORM”过渡到“ Rails Active Record”,但我找不到您该怎么做:$ this-> people()-> attach($ person ['id'], ['role'=> $ role]);说明...
class Person < ApplicationRecord
has_many :assignments, as: :assignable
has_many :roles, through: :assignments
end
class Role < ApplicationRecord
has_many :assignments
has_many :people, through: :assignments
end
class Assignment
belongs_to :role
belongs_to :assignable, polymorphic: true
end
您可以阅读更多Rails has_many :through Polymorphic Association by Sean C Davis