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

在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
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 模拟电路 logisim
  • ¥15 PVE8.2.7无法成功使用a5000的vGPU,什么原因
  • ¥15 is not in the mmseg::model registry。报错,模型注册表找不到自定义模块。
  • ¥15 安装quartus II18.1时弹出此error,怎么解决?
  • ¥15 keil官网下载psn序列号在哪
  • ¥15 想用adb命令做一个通话软件,播放录音
  • ¥30 Pytorch深度学习服务器跑不通问题解决?
  • ¥15 部分客户订单定位有误的问题
  • ¥15 如何在maya程序中利用python编写领子和褶裥的模型的方法
  • ¥15 Bug traq 数据包 大概什么价