الكؤوس المقدسة: البحث عن الأطفال في علاقة الكثير من واحد الى والمرجعية الذاتية

StackOverflow https://stackoverflow.com/questions/1220350

  •  10-07-2019
  •  | 
  •  

سؤال

في الكؤوس المقدسة،

وكيف يمكن للمرء أن يجد جميع الأطفال في علاقة واحد لكثير منها مثلا.

class Employee {
    static hasMany = [ subordinates: Employee ]
    static belongsTo = [ manager: Employee ]
}

وعن طريق مدير واحد، كيف للمرء الحصول على المرؤوسين من جميع المرؤوسين (مثل عبور رسم بياني الكائن)؟

هل كانت مفيدة؟

المحلول

وإغلاق متكررة يعمل إذا كنت لا ترغب في تعديل المجال. وإلا هل يمكن إضافة خاصية عابرة إلى فئة نطاق Employee مثل allSubordinates في هذا المثال:

class Employee {
    String name
    static hasMany = [ subordinates: Employee ]
    static belongsTo = [ manager: Employee ]
    static transients = ['allSubordinates']
    def getAllSubordinates() {
        return subordinates ? subordinates*.allSubordinates.flatten() + subordinates : []
    }
}

وهنا هو اختبار التكامل لرؤيتها في العمل:

import grails.test.*

class EmployeeTests extends GrailsUnitTestCase {
    Employee ceo
    Employee middleManager1, middleManager2
    Employee e1, e2, e3, e4, e5, e6

    protected void setUp() {
        super.setUp()
        ceo = new Employee(name:"CEO")
            middleManager1 = new Employee(name:"Middle Manager 1")
                e1 = new Employee(name:"e1")
                e2 = new Employee(name:"e2")
                e3 = new Employee(name:"e3")
            middleManager2 = new Employee(name:"Middle Manager 2")
                e4 = new Employee(name:"e4")
                e5 = new Employee(name:"e5")
                e6 = new Employee(name:"e6")

        ceo.subordinates = [middleManager1, middleManager2]
        middleManager1.subordinates = [e1,e2,e3]
        middleManager2.subordinates = [e4,e5,e6]
        assert ceo.save()
    }

    void testAllSubordinates() {
        def topLevelManager = Employee.get(ceo.id)
        assertNotNull(topLevelManager);
        assertEquals(8, topLevelManager.allSubordinates?.size())
    }
}

نصائح أخرى

 //Make a recursive closure
 def printAll

 printAll = { emp ->
    subordinates.each { 
                        println it
                        printAll emp
                      }
 }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top