doufang3001 2016-06-05 18:38
浏览 38

检查是否使用Laravel数据透视表设置了某些内容

I have a Laravel database with a table for tags, a table for items and a table for item_tag. The tags are hierarchical, and as a result, I'm trying to query which tags have been set inside a loop.

That's easy, I just use $item->tags and it gives me my tags in an accessible object, ready to loop through.

The problem appears when I want to check if a specific object is set, when showing a list of all tags. I'm using the following code for testing:

function buildTree($tags, $selected = null) {
    echo "<ul>";
        foreach($tags as $tag) {
            echo "<li>";
                if($selected[$tag->id]) {
                    echo "<strong>";
                }
                echo $tag->name;
                if($selected[$tag->id]) {
                    echo "</strong>";
                }
                if($tag->children) {
                    buildTree($tag->children);
                }
            echo "</li>";
        }
    echo "</ul>";
}
$item = Item::find(1);
$tags = Tag::whereNull('tag_id')->get();
buildTree($tags, $item->tags);

The expected output would be that each tag that is selected would come up as bold in the tree. Of course, if that had happened, I wouldn't be posting this. Instead, it just highlights the first item in the tree, even though it isn't selected. (That's because $selected isn't supposed to be addressed that way).

What's the correct way to get this information?

  • 写回答

2条回答 默认 最新

  • dougao9864 2016-06-05 18:52
    关注

    That's because $selected isn't supposed to be addressed that way

    Then how's it got to be addressed? Of course the answer lies there itself, since you rely on $selected for checking what tags were selected.

    As per your comment, the following should solve your problem

    Change your if condition from this -

    if($selected[$tag->id])
    

    To This -

    if(array_in($tag->id, $selected))
    
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度