获取 foreach 循环外部的行,但在循环内比较它们(智能模板)



这是我的问题 - 我有一个带有评论的页面,看起来像这样:

{foreach from=$comments item=row}
Here is the body of comment and like/unlike button
{/foreach}

我需要检查用户是否已经喜欢该评论,并根据该显示喜欢/不喜欢按钮。通常在 php 中我会做这样的事情:

- Query to retrieve all the comments from DB
- foreach loop to show them, like that:
foreach ($stmt as $comment) {
- another query inside of the foreach loop to find out data of users who 
already liked this comment.
- then if/else statement to choose which button to show
}

但是由于我使用的是 smarty,所以我无法在 foreach 循环中进行任何查询,而它是模板并且不允许使用逻辑代码。我需要检查的是:

{foreach from=$comments item=row}
{if {$comment_id} != {$row.id} && {$user_liked} != $user_id}
show like button
{/if}
{if {$comment_id} == {$row.id} && {$user_liked} == $user_id}
show dislike button
{/if}
{/foreach}

我的数据库结构,以便您了解这些行的含义:

Table `liking`:
-comment_id
-user_liked
Table `comments`:
-id
And $user_id is actually $_SESSION['user_id'];

所以问题来了: 如何从带有注释的 foreach 循环外部liking表中获取comment_id行和user_liked行,以便我可以在循环内将它们与注释进行比较? 我试图将它们全部获取,并在注释 foreach 循环中使用另一个 foreach 循环来获取它们,但它只是无法正常工作。Smarty引擎很酷,但是当涉及到这样的事情时,它真的很令人失望......感谢所有会尽力帮助我的人,我很高兴听到任何建议或建议!

您可以在获取注释 talbe 时获取 php 代码中的喜欢表。 例如:

select comment.*,(select count(*) from liking where liking.comment_id=comment.id and liking.user_liked={$_SESSION("user_id")) as liked from comment

在聪明中:

{foreach from=$comments item=row} {如果$row.liked==0} "显示赞"按钮 {其他} "显示不喜欢"按钮 {/if} {/foreach}

最新更新