def _merge_foreign_keys(fk_constraints, fk_relations):
    """
    Merge annotated foreign key relations into foreign key constraints.

    (Both constraints and relations are for the same table.)
    Add all relations, except if a matching constraint exists: then amend
    the constraint by adding cardinality information.
    """
    for rel in fk_relations:
        for constr in fk_constraints:
            if rel['fields'] == constr['fields']:
                r1 = rel['reference']
                r2 = constr['reference']
                if r1['datapackage'] == r2['datapackage'] and r1['resource'
                    ] == r2['resource'] and r1['fields'] == r2['fields']:
                    r2['cardinalitySelf'] = r1['cardinalitySelf']
                    r2['cardinalityRef'] = r1['cardinalityRef']
                    break
        else:
            fk_constraints.append(rel)
