拉拉维尔(Laravel)检索多行数据

3

我有一个三表关联查询的问题。我想获取一场电影和影院的场次。

我可以通过参数传递的 $id 获取到电影的 id。我想找到播放这部电影的影院。

以下是我的控制器:

public function ticketpage($id)
{
    $movie = Movie::find($id);
    $cinemas = Cinema::all();
    $sessions = Session::all();
    $query = Session::where('movie_id', "$id")->get();
    $count = count($query)-1;


    $cinemaId = $query[$count]['cinema_id'];
    $cinemaRow = Cinema::where('id', "$cinemaId")->get();

    return view('movies/ticketpage/index')
        ->with('cinemas', $cinemas)
        ->with('sessions', $sessions)
        ->with('movie', $movie)
        ->with('cinemaRow', $cinemaRow);
}

你可以看到,我不太确定如何使用我的 $query(检索具有该电影ID的所有会话)来检索具有该影院ID的所有行。

我尝试过使用 $query[count]['cinema_id],但它只会返回一个值,即最后一行的值。我希望它能返回所有行的值。我尝试使用 for 循环,但没有取得太大成功。

谢谢您的帮助!

4个回答

2

首先,我假设以下模式和关系已经建立。

| Movie | Cinema | Session   |
| ----- | ------ | --------- |
| id    | id     | id        |
|       |        | cinema_id |
|       |        | movie_id  |

这是我将根据您的说明获取播放电影的电影院并基于其 movie_id 检索的方法:

我可以访问作为参数传递的电影ID $id。 我想找到拥有该电影ID的电影院。.

public function ticketpage($id)
{
    // Get all Cinema which has the Session with the Movie.id
    $cinemas = Cinema::whereHas('sessions', function ($query) use ($id) {
        $query->where('movie_id', $id);
    })->get();

    return view('movies/ticketpage/index', [
        'cinemas' => $cinemas
    ]);
}

如果您想要获取电影院中所有电影场次,也可以通过获取Session并使用with('cinema')来实现。请告诉我,我可以更新答案。 - Mosufy
谢谢Mosufy。你知道是否可以使用相同的逻辑,但获取播放电影id 1和id 2的电影院吗?因此返回播放多部电影的电影院? - Hese
是的,这绝对是可能的。只需将 where 修改为 whereIn。例如:$query->whereIn('movie_id', $array_of_movie_ids); - Mosufy

1

try this :

public function ticketpage($id)
{
$movie = Movie::find($id);
$cinemas = Cinema::all();
$sessions = Session::all();
$query = Session::select('cinema_id')->where('movie_id', $id)->get();
//$count = count($query)-1;


//$cinemaId = $query[$count]['cinema_id'];
//$cinemaRow = Cinema::where('id', $cinemaId)->get();
$cinemaRow = Cinema::whereIn('id', $query)->get();

return view('movies/ticketpage/index', compact('cinemas', 'sessions', 'movie', 'cinemaRow'));

// No need for all the 'withs'
//return view('movies/ticketpage/index')
//    ->with('cinemas', $cinemas)
//    ->with('sessions', $sessions)
//    ->with('movie', $movie)
//    ->with('cinemaRow', $cinemaRow);
}

0

将这两个替换为你的代码,然后尝试一下,应该可以工作:

$query = Session::select('cinema_id')->whereMovie_id($id)->get();
$cinemaWithSession = Cinema::whereId($query)->get();

0
如果您拥有电影ID并且在cinemas表中有一个movie_id列,则可以使用以下查询检索电影院:
public function ticketpage($id)
{
    $cinemas = Cinema::where('movie_id',$id)->get();
    return view('movies.ticketpage.index',compact('cinemas'));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接