dongzhuandian3292 2018-07-07 16:35
浏览 44
已采纳

显示具有多对多关系laravel 5.4的字段

I'm the beginner of laravel 5.4. I just want to ask. I want to display in Assignments table the Collectors but it doesn't show.

Screenshot of the Assignments Index

Code in my Assignment index.blade.php

<td>{{ $assignment->collector['firstname'] }} {{ $assignment->collector['lastname'] }}</td> 

Assignment.php model

public function collectors()
{
    return $this->belongsToMany(Collector::class);
}

Collector.php model

public function assignments()
{
    return $this->belongsToMany(Assignment::class);
}

AssignmentsController

public function index()
{
    $assignments = Assignment::all();

    return view('assignments.index', compact('assignments'));
}

I search to how to display the collectors with both many to many relationship. I read the doc about using pivot but I had still errors about that. Can you help me resolving this? Thanks

  • 写回答

1条回答 默认 最新

  • douhu2890 2018-07-07 16:45
    关注

    $collector is an object, not an array. Use -> syntax to access properties on individual collector models:

    $collector->firstname
    

    Since the relationship is many to many you need two loops:

    @foreach($assignments as $assignment)
         @foreach($assignment->collectors as $collector)
            <td>{{ $collector->firstname }} {{ $collector->lastname }}</td>
        @endforeach
    @endforeach
    

    If you find you often need two fields together, like first and last names, you can create an accessor on the Collector model to easily join them:

    public function getFullNameAttribute()
    {
        return $this->getAttribute('firstname') . ' ' . $this->getAttribute('lastname');
    }
    

    Allowing you to then do:

    @foreach($assignments as $assignment)
         @foreach($assignment->collectors as $collector)
            <td>{{ $collector->fullname }}</td>
        @endforeach
    @endforeach
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流