![](/img/trans.png)
[英]How to insert id from both tables into pivot table using laravel query builder
[英]Insert records to either two tables or one table depending on if a record exists or not using Laravel query builder
我正在嘗試將記錄插入到兩個表或一個表中,具體取決於記錄是否存在。
第一表作者
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”的作者,但如果作者確實存在於數據庫中,則獲取作者 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"]
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.