douyu0792 2018-10-17 16:10
浏览 179
已采纳

在laravel中更改foreach中的属性

So I'm using laravel, and I have a table with id, category_name, parent_id, desc, and url.

Then in the view, I foreach the table with this code:

@foreach($categories as $category)
    <tr class="gradeX">
        <td>{{ $category->id }}</td>
        <td>{{ $category->name }}</td>
        <td>{{ $category->parent_id }}</td>
        <td>{{ $category->description }}</td>
        <td>{{ $category->url }}</td>
        <td class="center">
            <a href="{{ url('/admin/edit-category/'.$category->id) }}" class="btn btn-primary btn-mini">Edit</a> 
            <a href="{{ url('/admin/delete-category/'.$category->id) }}" class="delCat btn btn-danger btn-mini">Delete</a>
        </td>            
    </tr>
@endforeach

now, instead of showing parent_id, I want to show the parent category name. I've tried a lot of things but nothing work.

I know this might be a very easy question, but I'm just started learning web development by myself. So please bear with me.

Thank you.

  • 写回答

1条回答 默认 最新

  • dongzecai0684 2018-10-17 16:43
    关注
    1. Define the parent relationship in the Category model. https://laravel.com/docs/5.7/eloquent-relationships
    2. Eager load that relationship in the query where you are fetching the categories. https://laravel.com/docs/5.7/eloquent-relationships#eager-loading
    3. Access the loaded relationship in the view, eg. $category->parent->name
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集