首页 > 解决方案 > 多重关系 Laravel - 对象中的对象

问题描述

我想使用 Laravel Eloquent 来建立关系,但是我在访问关系中的特定过滤对象时遇到问题。

我的对象:

courses:  
  id - integer
  name - string

contents:
  id - integer
  name - string

course_contents:
  id - integer
  course_id - integer
  content_id - integer

我想按课程获取内容。直到现在我只能过滤 course_contents 来过滤内容

我的控制器:

Course::hasContents()->find($id);

课程模式

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

    public function scopeHasContents($query)
    {
        $query->with(['contents' => function($contentQuery) {
            $contentQuery->has('content')->with('content');
        }]);
    }

课程内容模型:

public function content()
    {
       return $this->hasOne('App\Content', 'id');
    }

我的 json 返回(课程查找):

{  
    "id":1,
    "name":"Course Example 1",
    "contents":[  
        {  
            "id":1,
            "course_id":1,
            "content_id":1,
            "deleted_at":null,
            "created_at":"2019-07-16 17:31:05",
            "updated_at":"2019-07-16 17:31:05",
            "content":{  
                "id":1,
                "name":"Content Example 1",
                "deleted_at":null,
                "created_at":"2019-07-16 17:31:05",
                "updated_at":"2019-07-16 17:31:05"
            }
        },
        {  
            "id":2,
            "course_id":1,
            "content_id":2,
            "deleted_at":null,
            "created_at":"2019-07-16 17:31:05",
            "updated_at":"2019-07-16 17:31:05",
            "content":{  
                "id":2,
                "name":"Content Example 2",
                "deleted_at":null,
                "created_at":"2019-07-16 17:31:05",
                "updated_at":"2019-07-16 17:31:05"
            }
        },{ ... }
    ],
}

我需要的:

{  
    "id":1,
    "name":"Course Example 1",
    "contents":[  
        {  
            "id":1,
            "name":"Content Example 1",
            "deleted_at":null,
            "created_at":"2019-07-16 17:31:05",
            "updated_at":"2019-07-16 17:31:05"

        },
        {  
            "id":2,
            "name":"Content Example 2",
            "deleted_at":null,
            "created_at":"2019-07-16 17:31:05",
            "updated_at":"2019-07-16 17:31:05"

        },{ ... }
    ],
}

标签: laraveleloquent-relationship

解决方案


首先,你需要稍微调整一下关系。您有多对多的关系,因此模型应如下所示:

Course.php

public function contents()
{
    return $this->belongsToMany(Content::class, 'course_contents');
}


Content.php

protected $hidden = ['pivot'];

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


您可以按以下方式检索contents数据:例如:您想获取课程的所有内容1

Content::whereHas('courses', function($query) {
    $query->where('courses.id', 1);
})->get();

// You need to pass course id dynamically but for demonstration, I hard coded it.

这将为您提供以下结果:

array:1 [
  0 => array:2 [
    "id" => 1
    "name" => "Content 1"
  ]
]

推荐阅读