我有三张桌子,叫做分类,季节和电影。
类别表
+----+---------+------------+-------------+ | id | name | slug | created_at | +----+---------+------------+-------------+ | 1 | It | it-2017 | SOME TIME | | 2 | Another | another | SOME TIME | | 3 |SpiderMan| spider-man | SOME TIME | | 4 | Cars 3 | cars-3 | SOME TIME | +----+---------+------------+-------------+
seasons table
+----+---------+------------+-------------+ | id | number |category_id | created_at | +----+---------+------------+-------------+ | 1 | 1 | 2 | SOME TIME | | 2 | 2 | 2 | SOME TIME | | 3 | 1 | 3 | SOME TIME | | 4 | 3 | 1 | SOME TIME | +----+---------+------------+-------------+
movies table
+----+---------+------------+-------------+ | id | name | slug | season_id | +----+---------+------------+-------------+ | 1 | Pilot | pilot | 1 | | 2 | Second | second | 1 | | 3 | Third | third | 1 | | 4 | Fourth | fourth | 1 | +----+---------+------------+-------------+
And I made that URL is going to something like this
mywebpage.com/serie/{category_slug}/season-{season_number}
But where I go to this URL, query is going to show all movies in all seasons.Not the season from current category.
My Controller
public function getMovies($category_slug, $season_number)
{
$categories = Category::where('slug', $category_slug)->get();
$seasons = Season::with('movies')->where('number', $season_number)->get();
return view('routes.getMovies', compact('categories', 'seasons'));
}
我的视图getMovies.blade.php
@foreach($categories as $category)
@foreach ($seasons as $season)
@foreach ($season->movies as $movie)
Season - {{ $season->number }}
{{ $movie->name }}
{{ $movie->description }}
@endforeach
@endforeach
@endforeach
我的输出和所有类别的第一季一样,但我只想显示当前类别的季节。
最佳答案
首先,确保在你的模型上设置了正确的关系
电影模型
public function season()
{
return $this->belongsTo(Season::class, 'season_id');
}
季节模型
public function category()
{
return $this->belongsTo(Category::class, 'category_id');
}
然后,下面将得到具有特定季节编号和特定类别slug的所有电影
$movies = Movie::whereHas('season', function ($season) use ($season_number) {
$season->where('number', $season_number);
})
->whereHas('season.category', function ($category) use ($category_slug) {
$category->where('slug', $category_slug);
})
->with('season')
->get();
在视野中
@foreach ($movies as $movie)
Season - {{ $movie->season->number }}
{{ $movie->name }}
{{ $movie->description }}
@endforeach
关于php - 查询列在另一个表中的位置-Laravel,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46401758/