laravel - 多重关系 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"
},{ ... }
],
}
解决方案
首先,你需要稍微调整一下关系。您有多对多的关系,因此模型应如下所示:
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"
]
]
推荐阅读
- javascript - 如何使用 jquery 最好地访问 DOM-Element 的 value 属性?
- database - mongodb 中没有具有管理员权限的用户 - 如何创建具有管理员权限的用户?
- c++ - Unexpected variable values reading from file (ESP32)
- typescript - What would be the Typescript type for a module path? (for IDE autocompletion and static checking)
- python - How to exit when task is finished in asyncio
- javascript - Toggling class on scroll when div enters viewport with CSS scroll-snap
- javascript - How to show script having display none
- python - How can I make a python function that returns a random number using the objects in a list as probability weights?
- c - How can I turn my code into an actual aplication for windows?
- scala - In scala, what can be done to prevent compiler from cyclic summoning of implicit premises? And how to avoid them