我有3张名为类别,季节和电影的表格。
类别表
+----+---------+------------+-------------+ | 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 | +----+---------+------------+-------------+
四季表
+----+---------+------------+-------------+ | 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 | +----+---------+------------+-------------+
电影表
+----+---------+------------+-------------+ | id | name | slug | season_id | +----+---------+------------+-------------+ | 1 | Pilot | pilot | 1 | | 2 | Second | second | 1 | | 3 | Third | third | 1 | | 4 | Fourth | fourth | 1 | +----+---------+------------+-------------+
我说这个网址会是这样的
mywebpage.com/serie/ {category_slug} / {来临吧} season_number
但是,在我转到此网址时,查询将显示所有季节中的所有电影。 不是当前类别的季节。
我的控制器
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
我的输出就像所有类别的第1季一样,但我只希望显示当前类别的季节。
答案 0 :(得分:2)
首先,确保在模型上设置正确的关系
电影模特
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
答案 1 :(得分:0)
试试这个:
$categories = Category::where('slug', $category_slug)->first()->id;
$seasons = Season::with('movies')->where('number', $season_number)->where('category_id', $categories)->get();