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

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同