【问题标题】:Is there a way to get a nested Eloquent model based on ids from another table?有没有办法从另一个表中获取基于 id 的嵌套 Eloquent 模型?
【发布时间】:2021-04-17 15:02:24
【问题描述】:

嘿,stackoverflow

我目前正在构建一个课程应用程序,作为我的 laravel 项目的一部分。

我的问题在于 eloquent 如何处理模型关系,我对 eloquent 还是有点陌生​​,所以希望你能回答我的问题。

结构

课程有很多集,每集都有很多部分。

这意味着我在数据库中有 3 个表。 课程 -> course_episodes -> course_episode_sections

ID 表是我将课程与用户联系起来的地方 - course_users

现在我可以创建课程并正确输入所有数据。

问题

我需要检索用户购买的所有课程及其嵌套子项,这些子项在 course_users 表中与列 course_id 和 user_id

连接

课程结构

数据库中的相同结构

                course: {
                name: null,
                sub_title: null,
                estimate: null,
                trailer: null,
                type: null,
                text: null,

                course_episodes: [
                    {
                        name: null,
                        section: [
                            {
                                order: null,
                                type: null,
                                content: null,
                            },
                        ]
                    },
                ]

            }

模特图片

我现在的模型。

class CourseUsers extends Model {
protected $fillable = [
    'id',
    'course_id',
    'user_id',
    'active',
];

protected $hidden = [
    'deleted_at',
    'updated_at',
    'deleted_at'
];


public function courses()
{
    return $this->belongsToMany(Course::class);
}

public function user(){

    return $this->belongsTo(User::class);
}

public function scopeFindForUserId($query, $userId)
{
    return $query->where(function ($q) use ($userId) {
        $q->where(function ($q) use ($userId) {
            $q->where('user_id', $userId);
        });
    });
}

课程模式

class Course extends Model{
protected $fillable = [
    'id',
    'name',
    'sub_title',
    'type',
    'estimate',
    'trailer',
    'gateway_id',
    'text',
    'active',
];


protected $hidden = [
    'deleted_at',
    'updated_at',
    'deleted_at'
];


public function courseEpisode()
{
    return $this->hasMany(CourseEpisode::class);
}

public function courseUsers() {

    return $this->hasMany(CourseUsers::class);
}

public function scopeActive(Builder $builder)
{
    return $builder->where('active', true);
}

课程集模型

class CourseEpisode extends Model implements HasMedia {
use HasMediaTrait;

protected $fillable = [
    'id',
    'course_id',
    'order',
    'name',

];

protected $hidden = [
    'deleted_at',
    'updated_at',
    'deleted_at'
];

public function course()
{
    return $this->belongsTo(Course::class);
}

public function courseSection()
{
    return $this->hasMany(CourseEpisodeSection::class);
}

课程分集部分

class CourseEpisodeSection extends Model {

protected $fillable = [
    'id',
    'course_episode_id',
    'order',
    'type',
    'content'

];

protected $hidden = [
    'deleted_at',
    'updated_at',
    'deleted_at'
];

public function courseEpisode()
{
    return $this->belongsTo(CourseEpisode::class);
}

【问题讨论】:

  • 请在问题中发布代码而不是链接。
  • 不要将数据库表/模型发布为图像... Stackoverflow 支持表,否则代码是文本;使用正确的格式复制并粘贴到您的问题中。我们必须点击 8 个链接才能看到您的问题,这太过分了。
  • 您可能应该考虑的一件事是模型的命名方案。您目前有一个名为 CourseCourseEpisode 的模型,但后来有一个名为 CourseUsers 的模型。模型应该是单数的。
  • 所以如果我正确理解了这个问题,你想获得所有与用户连接的Courses 和相关的CourseEpisodes?我建议查看Eloquent relationship docs。根据您的描述,您需要的一切都应该在那里。
  • @YaakovAinspan 是的,我想查看 course_users 表并找到特定用户购买的所有课程。但我需要在此过程中获取所有课程及其嵌套子项。

标签: php laravel eloquent


【解决方案1】:

根据您的解释, course_users 表包含 Course 和 User 模型之间的多对多关系。在多对多关系的情况下,您实际上不需要 CourseUser 模型。这种保持多对多关系的表称为数据透视表。阅读更多来自Official Documentation

我只定义与您的 Course、User、CourseEpisode、CourseEpisodeSection 模型的关系。

课程.php

class Course extends Model
{
  public function courseEpisodes()
  {
    return $this->hasMany(CourseEpisode::class);
  }

  public function users()
  {
    return $this->belongsToMany(User::class,'course_users')->withPivot('active');
  }
}

CourseEpisode.php

class CourseEpisode extends Model
{
  public function courseSections()
  {
    return $this->hasMany(CourseSection::class);
  }
}

用户.php

class User
{
  public function courses()
  {
    return $this->belongsToMany(Course::class,'course_users')->withPivot('active');
  }
}

如果您想从用户那里获取所有子关系,请使用嵌套的eager loading

$user_with_nested_course_data = User::with('courses.courseEpisodes.courseSections')->find($id);

【讨论】:

  • 它有效!非常感谢您的帮助和非常有用的答案。 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-12
  • 2023-03-22
相关资源
最近更新 更多