我怎样才能将这张表格重新排列成另一个远离关系?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (17)

我在用户模型中使用了laravel hasmany关系,转换我的表格,如下所示(行到列):

致:

User模型:

public function meal(){
        return $this->hasMany(Meal::class);
    }

控制器:

 public function index()
    {
        $members = User::all();
        return view('admin.meal')->with([
            'members' => $members,
        ]);
}

@blade

 <table class="table table-striped @if(count($members)>7) table-responsive @endif ">


           <thead>
            <tr class="text-uppercase">
                {{--<th class="font-w700">Date</th>--}}
                @foreach($members as $member)
                    <th class="font-w700">{{str_limit($member->fname,5,'...')}}</th>
                @endforeach
            </tr>
            </thead>
            <tbody>
            @foreach($members as $member)
                <tr>
                    @foreach($member->meal as $meal)
                    <td><span class="font-w600">{{$meal->user_id}}</span></td>
                    @endforeach
                </tr>
            @endforeach
            </tbody>
        </table>
提问于
用户回答回答于

翻转您的查询结果,而不是返回成员,返回数据:

// Meal model
class Meal extends Model {
    public function user() {
        return $this->belongsTo(User::class);
    }
}

// Controller index
public function index()
{
    return view('admin.meal')->with([
        'meals' => Meal::with('user')->get()->groupBy('user_id'),
    ]);
}

// meals.blade.php
@foreach ($meals as $meal)
    <tr><td>{{ $meal->user->id }}</td></tr>
    <tr><td>{{ $meal->user->name }}</td></tr>
    <tr><td>{{ $meal->id }}</td></tr>
    <tr><td>{{ $meal->price }}</td></tr>
    <tr><td>{{ $meal->date_eaten }}</td></tr>
@endforeach

扫码关注云+社区

领取腾讯云代金券