如何避免关系"我的父亲是我的儿子"

时间:2017-01-02 05:20:15

标签: spring

我必须再次请你帮我完成我的项目。

我的关系类:

    $m = MailData::with('mail')->whereHas('mail',function($q) use($v){
           //filter the field favorite here..
           //example
           $q->where('favorite','like',$v);
         })->where('user_id', $userId)->orderBy('created_at', 'DESC')->take(10)->get();

如何在Spring应用程序中实现验证父母?我想禁止一个人的父亲或祖父作为他的儿子。

在客户端lourd是一个简单的情况,我做过滤列表。但是在数据库中怎么做?

2 个答案:

答案 0 :(得分:1)

创建一个addChild方法并递归地向上检查层次结构,以确保孩子不属于他们自己的祖先。

像这样:

public class GT_Member {

    private final GT_Member mother;

    private final GT_Member father;

    private final List<GT_Member> children;

    public GT_Member(final GT_Member mother, final GT_Member father) {
        this.mother = mother;
        this.father = father;
        this.children = new ArrayList<>();
    }

    /**
     * Add a child to this member.
     * @param child
     */
    public void addChild(GT_Member child) {
        if (child == null) {
            throw new IllegalArgumentException("Null children not allowed");
        }
        if (child.equals(this)) {
            throw new IllegalArgumentException("Can't add self as a child");
        }
        if (isAncestor(child)) {
            throw new IllegalArgumentException("Can't add an ancestor as a child");
        }
        children.add(child);
    }

    /**
     * Check if a member is an ancestor to this member.
     * @param member
     * @return True if the member is an ancestor, false otherwise
     */
    private boolean isAncestor(final GT_Member member) {
        // Check if the member is the mother or father
        return member.equals(mother) || member.equals(father)
                // Check if the member is an ancestor on the mother's side
                || (mother != null && mother.isAncestor(member))
                // Check if the member is an ancestor on the father's side
                || (father != null && father.isAncestor(member));
    }
}

答案 1 :(得分:0)

我会在两个级别接近支票 1.应用程序代码中的业务逻辑验证。 2.数据库触发器,以确保不会创建/更新此类不符合关系。