laravel 为下一个数据库请求获取数据库数据

laravel getting DB data for next DB request

public function show(\App\Models\Person $person){
    $casts = DB::table('casts')->where('person', '=', $person->id)->get();
    for($i=0;$i<count($casts);$i++){
        $movies = DB::table('movies')->where('id', '=', $casts[$i]->movie)->get();
    }
    return view('person.showPerson', compact('person', 'movies'));
}

当我想查看每个电影时。它显示我只是最后一个。那是因为 for,但是如果我删除 $casts[$i]。然后它不知道我指的是哪个 movieId(即 $casts->movie)。我想把它们都 foreach。如何发送所有 $movies(演员表中的人在其中)结果以供查看。我想我需要使用一些关系,但我不知道如何使用它们。感谢帮助

This is the casts structure
         +"id": "4",
         +"movie": "2",
         +"person": "1",
         +"role": "actor",
         +"created_at": "2020-12-21 19:19:58",
         +"updated_at": "2020-12-21 19:19:58",

您在 for 循环的每次迭代中都覆盖了 $movies 变量,因此它将只有最后一次迭代的值。

如果您不想使用模型和关系并想单独查询这些表,我不会使用 for 循环,因为您可以向数据库询问所有匹配集合的表。

我会从 casts 中获取所有电影字段并用它做一个 whereIn

$casts = DB::table('casts')->where('person', $person->id)->pluck('movie');
$movies = DB::table('movies')->whereIn('id', $casts)->get();