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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度