【问题标题】:Need help in grails model association在 grails 模型关联中需要帮助
【发布时间】:2013-10-11 10:58:53
【问题描述】:

我遇到了 Grails 模型关联的问题。问题来了:

  • Subscriber 和 Customer 是从 PartyRole 扩展而来的。
  • 一个客户可能有很多订阅者,一个订阅者属于客户。
  • 一个Party可能有很多PartyRole。
  • Person 和 Organization 从 Party 扩展而来。
  • 一个人属于组织。
  • 一个人有许多个人资料,一个个人资料属于个人。

现在我想编辑当前登录的用户(订阅者),它基本上是组织类型,意味着具有组织属性,如 orgName 和 orgSize。

我可以使用登录用户(订阅者)找到人员(名字和姓氏)和个人资料(电子邮件)详细信息,但无法获取组织详细信息。代码如下。

 def profile = {
    Subscriber loggedinSubscriber = Subscriber.get( springSecurityService.principal.id )
    if (loggedinSubscriber == null){
      redirect(controller: "login" , action:"login");
    }
    else{
      println loggedinSubscriber
      Party person = Person?.get(loggedinSubscriber.party.id)
      Party org = Organization?.get(loggedinSubscriber.party.id)
      Profile profile = person?.profile
      [userInstance: person, authorityList: sortedRoles()]
    }
  }

当我尝试使用

获取组织详细信息时
Party org = Organization?.get(loggedinSubscriber.party.id)

我得到了 null 值,但以同样的方式,我可以使用登录用户(订阅者)获取人员详细信息,并且两者都是从 Party 扩展的。`

知道如何获取组织详细信息。

人物:

package com.vproc.member

import com.vproc.enquiry.Enquiry;
import com.vproc.enquiry.Membership;
import com.vproc.enquiry.Notification;
import com.vproc.enquiry.Team;

class Person extends Party{

    String firstName
    String lastName

    Profile profile
    static belongsTo = [Organization]

    static constraints = {
        lastName nullable:true
        firstName blank:false

    }

}

**Organization:**

package com.vproc.member

import java.util.Date;

class Organization extends Party{

    String orgName 
    Person contact
    int orgSize
    boolean isVendor 

    static constraints = {
    }
}

简介:

package com.vproc.member

import java.util.Date;

import com.vproc.enquiry.Enquiry;
import com.vproc.enquiry.Membership;
import com.vproc.enquiry.Team;

class Profile {

    String emailAddress  //  field governed by privacy policy
    String phoneNumber   //  field governed by privacy policy
    Date dateCreated
    Date lastUpdated
    boolean isDefaultProfile
  String status
    static belongsTo = [person:Person]
    //ProfilePrivacyLevelEnum privacyLevel = ProfilePrivacyLevelEnum.Private

    static constraints = {
    }
}

订阅者:

package com.vproc.member

import java.util.Date;

import com.vproc.common.StatusEnum;
import com.vproc.enquiry.Discussion;
import com.vproc.enquiry.Enquiry;
import com.vproc.enquiry.Membership;
import com.vproc.enquiry.Notification;
import com.vproc.enquiry.SharedEnquiry;
import com.vproc.enquiry.Team;
import com.vproc.order.Seat;

class Subscriber extends PartyRole{

    transient springSecurityService

    String username
    String password
    boolean enabled
    boolean accountExpired
    boolean accountLocked
    boolean passwordExpired
    StatusEnum status
    Date dateCreated
    Date lastUpdated
    List<Contact> contacts ;

    static belongsTo = [ customer: Customer]
    static hasMany = [seats: Seat, ownedEnquiries: Enquiry,enquiresSharedWith: SharedEnquiry, enquiriesSharedBy: SharedEnquiry ,
         managedTeams: Team , memberships: Membership, contacts: Contact , sharedByContacts: SharedContact, sharedWithContacts: SharedContact,
          vContacts: VContact, partOf: VContact,  sharedbyVContacts: SharedVcontact, sharedWithVcontacts: SharedVcontact,
          notifications: Notification, discussions: Discussion]
    static mappedBy = [ managedTeams : "manager" , enquiresSharedWith: "sharedWith" , enquiriesSharedBy: "sharedBy"  ,
                                                   sharedByContacts : "sharedBy" , sharedWithContacts : "sharedWith" ,
                                                   vContacts: "forSubscriber"  ,  partOf :"ofContact",
                                                   sharedbyVContacts: "sharedby" , sharedWithVcontacts :"sharedWith"
                                                    ]


    static constraints = {
        username  validator : { val , obj ->
                                 if (obj.status != StatusEnum.Pending)
                                        val!= null
                              }
        username unique: true
        password validator : { val , obj ->
                                    if (obj.status != StatusEnum.Pending)
                                        val != null
                             }

        contacts nullable: true
        notifications nullable : true
        username nullable: true
        password nullable: true

    }

    static mapping = {
        password column: '`password`'
    }

    Set<Role> getAuthorities() {
        SubscriberRole.findAllBySubscriber(this).collect { it.role } as Set
    }

    def beforeInsert() {
        encodePassword()
    }

    def beforeUpdate() {
        if (isDirty('password')) {
            encodePassword()
        }
    }

    protected void encodePassword() {
        password = springSecurityService.encodePassword(password)
    }
}

派对:

包 com.vproc.member

导入 java.util.Date;

class Party {

    Date dateCreated
    Date lastUpdated

    static constraints = {
    }

    static mapping = {
        tablePerHierarchy false 
    }
}

派对角色:

包 com.vproc.member

导入 java.util.Date;

class PartyRole {

    Party party

    Date dateCreated
    Date lastUpdated
    static constraints = {
    }
    static mapping = {
        tablePerHierarchy false 
    }
}

引导带:

类引导程序 {

def init = { servletContext ->

def userRole = Role.findByAuthority('ROLE_USER') ?: new Role(authority: 'ROLE_USER').save(failOnError: true)
def adminRole = Role.findByAuthority('ROLE_COMPANY_ADMIN') ?: new Role(authority: 'ROLE_COMPANY_ADMIN').save(failOnError: true)
def guestRole = Role.findByAuthority('ROLE_GUEST') ?: new Role(authority: 'ROLE_GUEST').save(failOnError: true)
def csrRole = Role.findByAuthority('ROLE_CSR') ?: new Role(authority: 'ROLE_CSR').save(failOnError: true)

//PersonRole.create adminUser, adminRole
def address = new Address( city : 'Pune' , stateCode : 'MH' , countryCode : 'IN'   )

def adminProfile = Profile.findByEmailAddress('sachin.jha@gmail.com' )?: new Profile(
    privacyLevel: ProfilePrivacyLevelEnum.Private,
    emailAddress:  "sachin.jha@gmail.com" ,
    phoneNumber: "9325507992",
    status : 'Active'
    ).save( failOnError: true)

 def adminPerson = Person.findByProfile( adminProfile) ?: new Person( firstName: 'admin' , lastName : 'user' , profile: adminProfile).save( failOnError: true) ;
 def vprocOrganization = Organization.findByOrgName('VPROCURE') ?: new Organization ( orgName: 'VPROCURE' , orgSize : 100 , mailingAddress: address, contact: adminPerson ).save( failOnError: true)
 def vprocCustomer = Customer.findByParty( vprocOrganization) ?: new Customer ( party: vprocOrganization, status: StatusEnum.Active  ).save(failOnError: true) ;
 def adminUser = Subscriber.findByUsername('admin') ?: new Subscriber( username : 'admin' ,  password : 'passw0rd' , enabled: true , party: adminPerson, customer: vprocCustomer , status: StatusEnum.Active ).save( failOnError: true)

 if ( !adminUser.authorities.contains(adminRole)){
      SubscriberRole.create adminUser, adminRole
    }

  JSON.registerObjectMarshaller(Date) {
     return it?.format("MM/dd/yyyy")
  }

    def userProfile = Profile.findByEmailAddress( 'sachin.jha.user@gmail.com') ?: new Profile(
        privacyLevel: ProfilePrivacyLevelEnum.Private,
        emailAddress: "sachin.jha.user@gmail.com",
        phoneNumber : "9325507992",
        status : 'Active'
        ).save( failOnError: true)

    def userPerson = Person.findByProfile( userProfile) ?: new Person( firstName: 'plain' , lastName : 'user' , profile: userProfile).save( failOnError: true) ;
    def plainUser = Subscriber.findByUsername('plainuser') ?: new Subscriber( username: 'plainuser', password : 'passw0rd' , enabled: true , party: userPerson, customer: vprocCustomer , status: StatusEnum.Active ).save( failOnError : true )
    if ( !plainUser.authorities.contains(userRole)){
        SubscriberRole.create  plainUser, userRole
    }

/*vprocCustomer.addToSubscribers(amdinUser)
vprocCustomer.addToSubscribers(plainUser)
vprocCustomer.save( failOnError : true);*/

}

def destroy = {
}

}

【问题讨论】:

  • 你能展示你的域类吗?
  • 嗨@Eylen,我已经更新了域类的问题。请看一看。
  • 据我所知...您只是将订阅者与一个缔约方相关联,不可能使用相同的 ID 检索个人和组织...另外,如果您是确保您正在检索正确的人员实例(您最好检查一下)您应该能够轻松访问人员公司,只需执行 person.company
  • 嗨@Eylen,为了更好地理解,我在创建用户的地方添加了 BootStrap.groovy 文件。根据您的说法,我需要进行哪些更改才能在域类中检索组织详细信息。
  • 我认为您有两种选择,如果组织是与 Person 关联的组织,则只需使用 person.organization 访问它,它应该可以工作。如果是另一个组织,则必须在 PartyRole 中包含另一个 belongsTo (您可以添加 Person 和 Organization 以避免出现问题)...但是如果我很好地理解了您的问题,那么第一个解决方案应该可以解决问题。很抱歉没有添加代码,但我现在没有太多时间......

标签: grails associations


【解决方案1】:

只需更改 Person 域类

static belongsTo = [Organization]

static belongsTo = [organization:Organization]

并使用 person.organization 从人员实例访问组织信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多