duandai7601 2017-11-13 10:10
浏览 40
已采纳

在表中显示其他属性 - Laravel

My pivot table admin_user with additional attribute item_no. I am finding it hard to retrieve the additional attribute into my html table.

PS: i tried $admin->pivot->item_no in my table but i get an error trying to get a non-object

Admin

public function users()
    {
        return $this->belongsToMany('App\User')->withPivot('item_no')
        ->withTimestamps();
    }

admin_food

admin_id

user_id 

item_no

Controller

public function index()
     {
         $admins = Admin::where('id',1)->get();

         return view('index',compact('admins'));
     }

HTML

<table class="table" id="table"> 
<thead>
    <tr> 
    <th>Order No#</th>
    <th>Name</th>

    </tr>

</thead>
<tbody>
@foreach($admins as $admin)
<tr >
<td>{{$admin->name}}</td>

</tr>
@endforeach
</tbody>
</table>
  • 写回答

1条回答 默认 最新

  • dongyan6503 2017-11-13 10:38
    关注

    You access the item_id by access the pivot property of the user/related model.

    Your controller is returning a collection that has only one admin.

         $admins = Admin::where('id',1)->get();
    

    admins will be a collection of 1 admin that has id = 1.

    if this was on purpose, then you can access the item_id for every user related to this admin by this code:

    @foreach($admins as $admin)
        @foreach($admin->users as $user)
            <tr>
                <td>{{$user->name}}</td>
                <td>{{$user->pivot->item_id}}</td>
            </tr>
        @endforeach
    @endforeach
    

    To simplify:

    $admin = Amdin::first();
    $item_id = $admin->users()->first()->pivot->item_id
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分