gpt4 book ai didi

php - 查询列在另一个表中的位置 - laravel

转载 作者:行者123 更新时间:2023-11-29 02:13:07 24 4
gpt4 key购买 nike

我有 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  |+----+---------+------------+-------------+

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

我的输出类似于所有类别的第 1 季,但我只想显示当前类别的季节。

最佳答案

首先,确保在你的模型上设置了正确的关系

电影模特

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com