Represent relationships in json

5

What is the correct way or best practice for representing the relationships of a resource in json? As an example, I have the tables contrato , representante and empresa and the relationships contract N: 1 representative and company 1: N representative.

Which of the 3 following ways would be recommended? Note that in the third the fields need to have a complement in the name (eg: company_name) and this is a bit more laborious, I am using this way because I do not use any ORM.

EDIT: In this example I'm looking to query a contract with the endpoint /contratos/1

Examples:

1:

{
    "contrato_id": 1,
    "numero": 123456,
    "representante": {
        "representante_id": 2,
        "nome": "João"
        "empresa": {
            "empresa_id": 3,
            "nome": "Empresa",
        }
    }
}

2:

{
    "contrato_id": 1,
    "numero": 123456
    "representante": {
        "representante_id": 2,
        "nome": "João"
    },
    "empresa": {
        "empresa_id": 3,
        "nome": "Empresa",
    }
}

3:

{
    "contrato_id": 1,
    "numero": 123456
    "representante_id": 2,
    "nome_representante": "João"
    "empresa_id": 3,
    "nome_empresa": "Empresa"
}
    
asked by anonymous 14.03.2017 / 13:21

2 answers

7

The correct thing is the company object has a array representative , which in turn has a array contract >:

{
    "empresa": {
        "empresa_id": 1,
        "nome": "Empresa 1",
        "representantes": [{
            "representante_id": 1,
            "nome": "João",
            "contratos": [{
                "contrato_id": 1,
                "numero": 123456
            }, {
                "contrato_id": 2,
                "numero": 654321
            }]
        }, {
            "representante_id": 2,
            "nome": "José",
            "contratos": []
        }]
    }
}
    
14.03.2017 / 13:41
4

Fernando, thinking of coupling, I believe the ideal would be to have 3 sets of information interconnected.

Imagine that later when you need to change information on the Company / Client / Contract entities this would be less costly.

{
    "contrato":{
        "1": {
            "numero": 123456,
            "representante_id": 2,
            "empresa_id": 3
        }
    },
    "representante":{
        "2": {
            "nome": "João"
        }
    },
    "empresa":{
        "3": {
            "nome": "Empresa"
        }   
    }
}
    
14.03.2017 / 13:45