简体   繁体   English

Symfony 5.0.8 - 如何检查实体是否与 twig 中的关系记录?

[英]Symfony 5.0.8 - How to check if entity has relation record from with in twig?

I have User, Post and Bookmark entities.我有用户、帖子和书签实体。

inside the Bookmark entity:在书签实体内:

  • user -> ManyToOne用户 -> 多对一
  • Post -> ManyToOne发布 -> 多对一
  • date -> datetime日期 -> 日期时间

I'm displaying a post page like so "post/{id}" inside of the post display page, how can I check if the user has bookmarked this post?我在帖子显示页面内显示了一个类似“post/{id}”的帖子页面,我如何检查用户是否已将此帖子添加为书签?

Tried:试过:

{% if post.bookmarks.contains(app.user) %} 

{% if app.user.bookmarks.contains(post) %} // I thought it might do it magically

{% if app.user.bookmarks.contains({'post': post}) %}

I think it's looking for the bookmark object and I can't provide it without doing a for loop.我认为它正在寻找书签 object,如果不执行 for 循环,我将无法提供它。

Update:更新:

With the help of some people in the php chat came up with this solution:在 php 聊天中的一些人的帮助下,提出了这个解决方案:

{% if app.user.bookmarks|filter(b => b.property.id == property.id)|length %}

However, I'm wondering if there is a more effective solution that can be done in the controller and then passed to the view.但是,我想知道是否有更有效的解决方案可以在 controller 中完成,然后传递给视图。

Update更新

I don't like doing logic in the view, so the solution I found was in side he Post entity I created a function:我不喜欢在视图中做逻辑,所以我找到的解决方案是在我创建了一个 function 的Post实体中:

public function isPostBookmarkedByUser(User $user, Post $post): bool
{
    $bookmarks = $user->getBookmarks();

    foreach ($bookmarks as $bookmark) {
        if ($bookmark->getPost() === $post) {
            return true;
        }
    }
    return false;
}

Then I used this function inside the view like so:然后我在视图中使用了这个 function,如下所示:

{% if post.isBookmarkedByUser(app.user, post) %}
   <p>You bookmarked this post</p>
{% endif %}

Well, there's a lot of ways to obtain this, and there's not better or worst.嗯,有很多方法可以获得这个,没有更好或最坏的。
Depending on what makes sense in your domain, for example, you can provide a public method onto Post entity;例如,根据您的域中的意义,您可以在Post实体上提供一个公共方法; something like isBookmarkedByUser($user) or you can add it to User entity; isBookmarkedByUser($user)类的东西,或者您可以将其添加到User实体; like hasBookmarkedPost($post) .比如hasBookmarkedPost($post)
You can also make a Twig function and query directly the DB (avoiding looping and lazy-loading all the records of the Collection) or, maybe, you can loop directly in twig.您还可以制作Twig function并直接查询数据库(避免循环和延迟加载集合的所有记录),或者,您可以直接在 Z5669B8E487546F439F7020FC 中循环
As you can see from my answer, the possibilities are endless.从我的回答中可以看出,可能性是无穷无尽的。 Pick your posion: it's up to you.选择你的位置:这取决于你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM