V
V
Vladimir2019-08-20 11:20:36
symfony
Vladimir, 2019-08-20 11:20:36

symfony. Listing articles, capturing the name of the author of the article using one-to-many. How not to capture the entire Author object, but only its name?

I need to display a list of articles with the capture of the author's name without unnecessary information: email, password hash, etc.
Here is the main controller for listing articles on ch. page:

class MainController extends AbstractController
{
    /**
     * @Route("/", name="main")
     */
    public function index()
    {
        $rep = $this->getDoctrine()->getRepository(Article::class);

        $articles = $rep->findAll();

        return $this->render('main/index.html.twig', [
            'articles' => $articles,
        ]);
    }
}

$articles itself looks like:
Array
(
    [0] => App\Entity\Article Object
        (
            [id:App\Entity\Article:private] => 1
            [title:App\Entity\Article:private] => title
            [text:App\Entity\Article:private] => text
            [author:App\Entity\Article:private] => App\Entity\User Object
                (
                    [id:App\Entity\User:private] => 1
                    [email:App\Entity\User:private] => [email protected]
                    [roles:App\Entity\User:private] => Array
                        (
                            [0] => ROLE_ADMIN
                        )

                    [password:App\Entity\User:private] => $argon2id$v=19$m=65536,t=4,p=1$MU5HNEZleHpHZ2lsSHVoUg$lkUQSancg51pbdqDCWSiMd4Newk29/GqDsApt6gx7Cs
                    [first_name:App\Entity\User:private] => Vladimir
                    [last_name:App\Entity\User:private] => Vladimirov
                )

            [img_path:App\Entity\Article:private] => img
            [published_at:App\Entity\Article:private] => DateTime Object
                (
                    [date] => 2019-08-20 10:18:09.000000
                    [timezone_type] => 3
                    [timezone] => Europe/Moscow
                )

        )

)

Is it possible to leave only first_name and last_name from the User entity ? Can this be done in the controller or entity itself? Thanks in advance :) It should be something like this:
Result

5d5bacca74d98454804646.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2019-08-20
@prity

https://www.doctrine-project.org/projects/doctrine...

$query = $em->createQuery(
'SELECT NEW ArticleDTO(ar.title, ar.imagePath, ar.publishedAt, CONCAT(au.firstName, ' ', au.lastName)) 
FROM Article ar JOIN ar.author au');
$articles = $query->getResult(); // array of ArticleDTO

This can be placed somewhere in the repository in a separate method . Partial Object
may also be interesting , but here you risk forgetting that the object is not fully loaded and getting a bunch of hard-to-catch bugs

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question