Laravelクエリビルダーを使用してレコードが存在するかどうかに応じて、2つのテーブルまたは1つのテーブルにレコードを挿入します

BaconJuice

レコードが存在するかどうかに応じて、2つのテーブルまたは1つのテーブルにレコードを挿入しようとしています。

最初のテーブルの作成者

ID | Name
1  | Joe
2  | Sam

セカンドテーブルブック

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」の著者を追加しようとしていますが、著者がDBに存在する場合は、著者IDを取得して、本だけを挿入します。

これを手伝ってくれてありがとう!助けに感謝します。

アレクセイメンジェニン

ORMの使用を検討してください。Eloquentを使用すると、すべてのコードを次のように変更できます。

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

Query Builderを使用すると、次のことができます。

$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"]);

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Related 関連記事

ホットタグ

アーカイブ