невозможно получить желаемый формат JSON при создании API-интерфейса Laravel 5 - PullRequest
0 голосов
/ 20 сентября 2018

У меня есть следующая Template модель и TestCategory hasMany Test:

class Template extends Model
{
protected $table = 'test_templates';

protected $fillable = [
    'customers_id',
    'tests_categories_id',
    'tests_id'
];

public function customers(){
    return $this->belongsTo(Customer::class, 'customers_id');
}

public function testCategories(){
    return $this->belongsTo(TestCategory::class, 'tests_categories_id');
}

public function tests(){
    return $this->belongsTo(Test::class, 'tests_id');
}
}

И у меня есть следующий index метод, определенный в TemplateController

public function index($customerId)
{
$templates = Template::with( 'customers','testCategories','tests')
                      ->where('customers_id', $customerId)->get();
$templates = $templates->groupBy('tests_categories_id');
$templates = json_decode($templates, true);
$templates = array_values($templates);
return response()->json(['Status' => True, 'template' => $templates]);
}

Я получил следующий вывод json:

{
"Status": true,
"template": [
    [
        {
            "id": 1,
            "customers_id": 1,
            "tests_categories_id": 1,
            "tests_id": 1,
            "created_at": "2018-09-10 11:03:44",
            "updated_at": "2018-09-10 11:03:44",
            "customers": {
                "id": 1,
                "name": "Queen PVT.Ltd",
                "address": "gotham",
                "contact_number": "9842********",
                "created_at": "2018-09-10 11:03:43",
                "updated_at": "2018-09-10 11:03:43"
            },
            "test_categories": {
                "id": 1,
                "name": "General Tests",
                "created_at": null,
                "updated_at": null
            },
            "tests": {
                "id": 1,
                "tests_category_id": 1,
                "name": "Lamination",
                "created_at": null,
                "updated_at": null
            }
        },
        {
            "id": 2,
            "customers_id": 1,
            "tests_categories_id": 1,
            "tests_id": 2,
            "created_at": "2018-09-10 11:03:44",
            "updated_at": "2018-09-10 11:03:44",
            "customers": {
                "id": 1,
                "name": "Queen PVT.Ltd",
                "address": "gotham",
                "contact_number": "984*******",
                "created_at": "2018-09-10 11:03:43",
                "updated_at": "2018-09-10 11:03:43"
            },
            "test_categories": {
                "id": 1,
                "name": "General Tests",
                "created_at": null,
                "updated_at": null
            },
            "tests": {
                "id": 2,
                "tests_category_id": 1,
                "name": "Paper Type",
                "created_at": null,
                "updated_at": null
            }
        }
    ],
    [
        {
            "id": 7,
            "customers_id": 1,
            "tests_categories_id": 2,
            "tests_id": 8,
            "created_at": "2018-09-10 11:03:44",
            "updated_at": "2018-09-10 11:03:44",
            "customers": {
                "id": 1,
                "name": "Queen PVT.Ltd",
                "address": "gotham",
                "contact_number": "984******",
                "created_at": "2018-09-10 11:03:43",
                "updated_at": "2018-09-10 11:03:43"
            },
            "test_categories": {
                "id": 2,
                "name": "Scratch Test",
                "created_at": null,
                "updated_at": null
            },
            "tests": {
                "id": 8,
                "tests_category_id": 2,
                "name": "HRN Visibility",
                "created_at": null,
                "updated_at": null
            }
        }
    ]
]
}

Я хочу собрать все tests согласно test_categories без перепечатывания customers и test_categories следующим образом:

{
"Status": true,
"template": [
    [
        {
            "id": 1,
            "customers_id": 1,
            "tests_categories_id": 1,
            "tests_id": 1,
            "created_at": "2018-09-10 11:03:44",
            "updated_at": "2018-09-10 11:03:44",
            "customers": {
                "id": 1,
                "name": "Queen PVT.Ltd",
                "address": "gotham",
                "contact_number": "984*****",
                "created_at": "2018-09-10 11:03:43",
                "updated_at": "2018-09-10 11:03:43"
            },
            "test_categories": {
                "id": 1,
                "name": "General Tests",
                "created_at": null,
                "updated_at": null
            },
            "tests": {
                {
                "id": 1,
                "tests_category_id": 1,
                "name": "Lamination",
                "created_at": null,
                "updated_at": null
                },
                {
                "id": 2,
                "tests_category_id": 1,
                "name": "Paper Type",
                "created_at": null,
                "updated_at": null
                }
            }
        }
    ],
    [
        {
            "id": 7,
            "customers_id": 1,
            "tests_categories_id": 2,
            "tests_id": 8,
            "created_at": "2018-09-10 11:03:44",
            "updated_at": "2018-09-10 11:03:44",
            "customers": {
                "id": 1,
                "name": "Queen PVT.Ltd",
                "address": "gotham",
                "contact_number": "984265*****",
                "created_at": "2018-09-10 11:03:43",
                "updated_at": "2018-09-10 11:03:43"
            },
            "test_categories": {
                "id": 2,
                "name": "Scratch Test",
                "created_at": null,
                "updated_at": null
            },
            "tests": {
                {
                "id": 8,
                "tests_category_id": 2,
                "name": "HRN Visibility",
                "created_at": null,
                "updated_at": null
                }
            }
        }
    ]
]
}

1 Ответ

0 голосов
/ 21 сентября 2018

Если я правильно понимаю проблему, тесты разделяются на разные шаблоны, когда вы ожидаете, что некоторые из них будут связаны с одним и тем же шаблоном.

Это потому, что ваш класс Template хранит test_id, к которому он принадлежит, и он может хранить только 1 тест на шаблон.Поэтому, когда вы звоните Template::with('tests'), он может вернуть только один Test::class.

Поскольку вы ожидаете увидеть, что многие тесты принадлежат одному шаблону, а когда вы смотрите на связь между шаблоном и тестом, вы ожидаете, чтоШаблон имеет много тестов.Следовательно, ваш класс Template должен реализовывать отношение hasMany следующим образом:

class Template extends Model
{

protected $fillable = [
    'customers_id',
    'tests_categories_id' // notice the removal of the test_id which should also be removed from the test_templates migration
];
    ...

    public function tests(){
        return $this->hasMany(Test::class); //change belongsTo to hasMany
    }

    ...
}

Вместо хранения test_id в классе Template вы должны хранить template_id в своем классе Test и выглядеть примерно так:

class Test extends Model
{

protected $fillable = [
    ...
    'test_template_id' // This should be added to $fillable and the tests migration
    ...
];
    ...

    public function template(){
        return $this->belongsTo(Template::class, test_template_id);
    }

    ...
}

Теперь, когда вы звоните Template::with('tests'), он может вернуть много Test::class и должен соответствовать ожидаемому результату.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...