【问题标题】:Getting rows outside of the foreach loop but comparing them inside of it (smarty template)在 foreach 循环之外获取行但在其中比较它们(智能模板)
【发布时间】:2017-06-16 18:59:24
【问题描述】:

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

{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'];

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

【问题讨论】:

    标签: php foreach smarty smarty3


    【解决方案1】:

    在获取评论列表时,您可以在 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=$cmets item=row} {如果 $row.liked==0} 显示喜欢按钮 {别的} 显示不喜欢按钮 {/如果} {/foreach}

    【讨论】:

    • 感谢您的回答!但现在我得到的只是这个 - Warning: Illegal string offset 'liked'
    • 你必须检查你的php代码,喜欢的字段没有分配给smarty。你能在这里粘贴更多代码吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    相关资源
    最近更新 更多