根据记录是否存在使用 Laravel 查询生成器将记录插入到两个 table 或一个 table

Insert records to either two tables or one table depending on if a record exists or not using Laravel query builder

我正在尝试将记录插入到两个 table 或一个 table 中,具体取决于记录是否存在。

第一 table 位作者

ID | Name
1  | Joe
2  | Sam

第二本table本书

ID | author_ID | Book
1  | 2         | Book1
2  | 2         | BookYYY
3  | 1         | BookABC

我想要完成的是首先检查作者是否存在,如果不存在则插入作者和他的书,如果确实存在则只插入具有正确作者 ID 的书

这是我迄今为止尝试过的方法,但似乎没有用。

$result = DB::table('authors')
            ->where('name',  $data['author_name'])
            ->where('username', $data['author_username'])->pluck('id');

if(is_null($result)){
    //Not in table add new author
    $id = DB::table('authors')->insertGetId(
        ['name' =>  $data['author_name'], 'username' => $data['author_username']]
    );
    //Add book
    DB::table('books')->insert(
        ['author_id' => '.$id.', 'name' => "Book777"]
    );
}
else{
    //Is in table insert just book
    DB::table('books')->insert(
        ['author_id' => '.$result.', 'name' => "Book777"]
    );
}

所以我尝试添加书名为 "Book777" 的作者,但如果作者确实存在于数据库中,请获取作者 ID 并仅插入书。

谢谢大家帮我解决这个问题!感谢任何帮助。

考虑使用 ORM。使用 Eloquent,您可以将所有代码更改为:

$author = Author::firstOrCreate(['name' => $data['author_name'], 'username' => $data['author_username']]);
$author->books()->create(['name' => 'Book777']);

使用查询生成器,您可以这样做:

$attributes = [
    'name' => $data['author_name'],
    'username' => $data['author_username']
];

$author = DB::table('authors')->where($attributes)->first();
$authorId = is_null($author) ? DB::table('authors')->insertGetId($attributes) : $author->id;
DB::table('books')->insert(['author_id' => $authorId, 'name' => "Book777"]);

我不确定它是否有效,但希望这对您有所帮助

    $result = DB::table('authors')
                ->where('name',  $data['author_name'])
                ->where('username', $data['author_username'])->pluck('id');

    if(!empty($result)){
        //Is in table insert just book
        DB::table('books')->insert(
            ['author_id' => $result, 'name' => "Book777"]
        );
    }
    else{
        //Not in table add new author
        $id = DB::table('authors')->insertGetId(
            ['name' =>  $data['author_name'], 'username' => $data['author_username']]
        );
        //Add book
        DB::table('books')->insert(
            ['author_id' => $id, 'name' => "Book777"]
        );
    }