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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题