Symfony, return a Json with all the fields

0

I have an entity named "Courses" that has a series of attributes and one of them is "shop" which is an onetomany relation with a Entity "Shop"

In the controller I have done an action that what it does is to return a JSON by applying a series of search filters, this I use later with bootstrap-table to present it visually

In the controller I have this code

/**
 * @param Request $request
 * @Route("/find/", name="admin_curso_find")
 * @return JsonResponse
 */
public function findAcademicProgram(Request $request)
{
    $search=$request->query->get('search');

    $em = $this->getDoctrine()->getManager();
    $query = $em->createQuery(
        'SELECT a FROM AppBundle:AcademicAgreement a 
             where a.code LIKE :search ')
        ->setParameter('search', '%' . $search . '%');

    $ap = $query->getArrayResult();

    return new JsonResponse($ap);
}

And this returns a JSON of this style

  

[{"id": 1, "code": "12213", "enabled": false, "createdAt": null, "updatedAt": null, "disabledAt": {"date": "2018-01 -18   09: 36: 49.000000 "," timezone_type ": 3," timezone ":" Europe / Berlin "}}

But in the entity I have another field like the "shop" which is the relationship I mentioned earlier and this field the previous code does not return it to me.

Thanks

    
asked by ilernet 05.02.2018 в 17:23
source

2 answers

1

What you must do, since you are creating a query using $em->createQuery() is to establish the relationship directly using a Join, since you are not using the doctrine mappers, but creating a 'manual' query

should look something like the following

$query = $em->createQuery(
        'SELECT c, s FROM bundle::curso c 
         join bundle:shop as s where c.id = s.curso_id 
             where c.code LIKE :search ')
        ->setParameter('search', '%' . $search . '%');
    
answered by 20.03.2018 / 19:11
source
0

In general, Doctrine has set as default the "Lazy Loading" pattern for relations between entities. That's why, when you bring your data, convert it to an array and then convert it as json you do not see the related entity.

The correct way to return entities in JSON or Array format is to use a serializer . This allows you to have exact control over how you are going to show or expose the properties of your entity.

I recommend JMS Serializer or directly Symfony component

Both are quite easy and intuitive to use.

I hope I have helped you!

    
answered by 06.02.2018 в 16:57