Laravel Eloquent Relationship - 将数据插入多个表格

Day*_*eak 5 php mysql database laravel eloquent

我有以下结构:

3桌:电影,演员,流派

电影表架构:

Schema::create('movies', function (Blueprint $t) {
        $t->increments('id');
        $t->string('title');
        $t->integer('genre_id')->unsigned();
        $t->foreign('genre_id')->references('id')->on('genres');
        $t->string('genre');
        $t->timestamps();
    });
Run Code Online (Sandbox Code Playgroud)

类型表架构:

Schema::create('genres', function (Blueprint $t) {
        $t->increments('id');
        $t->string('name');
        $t->timestamps();
    });
Run Code Online (Sandbox Code Playgroud)

演员表架构:

Schema::create('actors', function (Blueprint $t) {
        $t->increments('id');
        $t->string('name');
        $t->timestamps();
    });
Run Code Online (Sandbox Code Playgroud)

电影模态:

public function genre()
{
    return $this->belongsTo('App\Genre');
}
public function actor()
    {
        return $this->belongsToMany('App\Actor');
    }
Run Code Online (Sandbox Code Playgroud)

类型莫代尔:

public function movie()
{
    return $this->hasMany('App\Movie');
}
Run Code Online (Sandbox Code Playgroud)

演员莫代尔:

public function movie()
{
    return $this->belongsToMany('App\Movie');
}
Run Code Online (Sandbox Code Playgroud)

形成:

<form method="post" action="{{ route('movies.insert') }}">
   <input type="text" name="movieName" id="movieName">
   <input type="text" name="actorName" id="actorName">
   <input type="text" name="genre" id="genre">
   <button type="submit">Add</button>
</form>
Run Code Online (Sandbox Code Playgroud)

我使用以下控制器方法从表单发布数据,一切正常,但当我提交2个具有相同类型的电影,例如"动作/剧情"时,我在流派表中得到2个单独的条目,如:

id:1 name:Action/Drama

id:2 name:Action/Drama

对于特定类型类型反复使用单个ID的最佳方法是什么?例如,如果我添加10个流派类型为"动作/剧情"的电影,那么"电影"表中的"genre_id"外键应该只显示一个特定的id,它与流派表的"动作/戏剧"ID相对应.希望有道理:/

控制器方法:

public function addMovies(Request $request)
{
    $genre = new Genre;
    $genre->name = $request->input('genre');
    $genre->save();

    $movie = new Movie;
    $movie->title = $request->input('movieName');
    $movie->genre = $request->input('genre');
    $movie->genre()->associate($genre);
    $movie->save();

    $actor = new Actor;
    $actor->name = $request->input('actorName');
    $actor->save();
    $actor->movie()->save($movie);

    return redirect()->route('movies.search');
}
Run Code Online (Sandbox Code Playgroud)

输出表应如下所示:

在此输入图像描述

注意:我还有一个数据透视表,它将电影与演员连接以促进多对多关系,但我没有将它包括在这里.

小智 4

好吧,你每次都会明确保存一个新的类型,这就是你得到重复项的原因。你想做的是这样的

$genre = Genre::firstOrCreate("name", $request->input('genre'));
Run Code Online (Sandbox Code Playgroud)

然后你将电影分配给类型