有序结果使用Laravel在关系中设置

时间:2015-05-12 18:18:52

标签: php sql laravel eloquent laravel-5

我有一个具有这种结构的表结构:

User (has many) Subjects (has many) Modules (has many) Topics (has many) Notes

我在每个表中都有外键,如下所示:

Subject (user_id), Modules(subject_id), Topics(module_id), Notes(topic_id)

我希望能够访问按创建日期排序的用户创建的所有注释。这可以使用查询构建器吗?

Note.php

class Note extends Model implements SluggableInterface
{

    use SluggableTrait;

    protected $sluggable = [
        'build_from' => ['question', 'id'],
        'save_to'    => 'slug'
    ];
    protected $fillable = ['question', 'answer', 'topic_id'];

    public function topic()
    {
        return $this->belongsTo('App\Topic');
    }


}

Topic.php

class Topic extends Model implements SluggableInterface
{

    use SluggableTrait;

    protected $sluggable = [
        'build_from' => ['title', 'id'],
        'save_to'    => 'slug'
    ];
    protected $fillable = ['title', 'module_id'];

    public function notes()
    {
        return $this->hasMany('App\Note');
    }

    public function module()
    {
        return $this->belongsTo('App\Module');
    }

}

2 个答案:

答案 0 :(得分:1)

由于命名惯例,我不是100%肯定:

$user = User::with(['subjects.modules.topics.notes' => function($query)
{
    $query->orderBy('created_at')
}])->whereId($user_id)->first();

dd($user);

在评论中向我提供反馈意见。

答案 1 :(得分:1)

有几种方法可以做到这一点。如果你想使用你的关系,你需要嵌套几个循环来穿过整个"树"关系。

$user = User::with('subjects.modules.topics.notes')->find($user_id);

$notes = new Illuminate\Database\Eloquent\Collection;

foreach($user->subjects as $subject) {
    foreach($subject->modules as $module) {
        foreach($module->topics as $topic) {
            foreach($topic->notes as $note) {
                $notes->add($note);
            }
        }
    }
}

$notes = $notes->sortBy('created_at');

至于通过数据库设计更容易,这是一个棘手的问题,而不知道你的应用程序的其余部分在做什么。如果这是你有任何笔记的唯一地方,那么我想说它可能是理想的解决方案。如果其他地方也需要笔记,那么这可能是一个问题。

另一种方法必须是使用查询构建器,它不需要您遍历任何结果集,但需要您编写sql。我不会说它更简单或更容易。

$notes = \DB::table('users')
    ->select('notes.*')
    ->join('subjects', 'users.id', '=', 'subjects.user_id')
    ->join('modules', 'subjects.id', '=', 'modules.subject_id')
    ->join('topics', 'modules.id', '=', 'topics.module_id')
    ->join('notes', 'topics.id', '=', 'notes.topic_id')
    ->where('users.id', $user_id)
    ->get();