Laravel - 循环来自多个表的所有数据

时间:2017-05-26 07:54:17

标签: laravel-5 relationship

美好的一天。我已经研究过它,但没有与我的问题相匹配。这是场景。我有courses表和3个表,assignmentsquizzesreports。现在,我想要的是,从表assignmentsquizzesreports以及循环中获取所有记录通过特定course下方的所有记录。

示例输出:订单应该根据第一个创建的项目。
Course1
Assignment1
Quiz1
Quiz2
Assignment2
Report1

如何使用三个不同的表格执行此操作?我知道如何使用基本的many to many关系,但为此。我真的很累。需要帮助的人。

Note: I'm using Laravel5.1

Update1 — Course.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Course extends Model
{
    protected $fillable = [];

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

    public function quizzes(){
        return $this->belongsToMany('Quiz');
    }

    public function reports(){
        return $this->belongsToMany('Report');
    }

}

根据要求更新UPDATE2

<div class="table">
                <table class="tabled">
                    <thead>
                        <tr>
                            <th>x</th>
                        </tr>
                    </thead>
                    <tbody>
                    @foreach($course_items as $course_item)
                        <tr>
                            <td>
                                <a href="#">{{ $table_name }} {{ $course_item->name }}</a>
                            </td>
                        </tr>
                    @endforeach
                    </tbody>
                </table>
            </div>

1 个答案:

答案 0 :(得分:2)

根据您的问题提供的有限信息,您需要将您的关系合并到一个集合中。

如果可行的话,使用工会将是一个更好的解决方案,以提高效率,但是嘿嘿。

// Prepare not deleted scope
// I would suggest using Laravel's SoftDeletes, as it'll be better than writing your own implementation. But if not, you would be better to create this as a reusable scope on your model
$notDeletedScope = function ($query) {
    return $query->where('deleted', 0);
};

// Find course with non-deleted relations
$course = Course::with([
        'assignments' => $notDeletedScope,
        'reports'     => $notDeletedScope,
        'quizzes'     => $notDeletedScope,
    ])
    ->findOrFail($id);

// Combine relations into single collection
$merged = collect($course->assignments);
$merged = $merged->merge(collect($course->quizzes));
$merged = $merged->merge(collect($course->reports));

// Sort merged relations by created_at
$merged = $merged->sortBy('created_at');

@foreach ($merged as $relation)
    @if ($relation->type === 'assignment')
        // ...
    @elseif ($relation->type === 'quiz')
        // ...
    @elseif ($relation->type === 'report')
        // ...
    @endif
@endforeach

添加到每个模型:

public function getTypeAttribute()
{
    return snake_case(substr(strrchr(get_class($this), '\\'), 1));
}