簡體   English   中英

使用save()方法保存新的Model時返回關系數據和新的Model object

[英]Return relationship data along with the new Model object when saving the new Model using the save() method

$user = User::find(1);
$post = new Post();
$user->posts()->save($post);

我想在不對數據庫進行額外查詢的情況下訪問新的PostUser 如果我執行以下操作,它將查詢User的數據庫:

$userPost = $post->user;

我知道我可以只做$userPost = $user ,但出於某些原因,我不想那樣做。

所以我的問題是,在使用save()Post時是否可以預先加載User

我只是嘗試以下方式以最少的查詢保存新帖子。

$user = User::with('posts')->find(1);

// create new post , but not save it yet
$post = new Post(['title' => 'lorem ipsum', 'body' => 'something something']);

// push it to user posts collection
$user->posts->push($post);

// and now save it
$user->posts()->save($post);

// then check the content, post should now have id and timestamps
dd($user, $user->posts);

新的 Post 有 id 和時間戳,無需重新加載所有帖子,為您節省一點性能和執行時間。

有人可能會問,執行了多少查詢?

  1. “select * from "users" where "users"."id" =? limit 1"
  2. “從“帖子”中選擇 *,其中“帖子”。“user_id”在 (1) 中”
  3. “插入“帖子”(“標題”、“正文”、“user_id”、“updated_at”、“created_at”)值(?、?、?、?、?)返回“id”

我在事務之前使用DB::enableQueryLog()並在事務之后使用DB::getQueryLog()來跟蹤這些查詢。

...

關於你的問題: $post->user
不幸的是,這仍然會觸發額外的查詢

"select * from "users" where "users"."id" = 1 limit 1"


現在讓我們比較好舊的向用戶添加帖子的步驟。 (第二個選項)

  • $id = 1;
  • $user = User::with('posts')->find($id); // needs 2 queries
  • $post = Post::create(['user_id' => $id, 'title'.... ]); // 3rd query
  • $user->load('posts'); // 第 4 個查詢(但這是可選的)
  • $userPost = $post->user; // and last query

總共需要執行 4 或 5 個查詢,具體取決於您是否需要將所有帖子加載為用戶的孩子。

在性能方面,cpu 使用率和執行時間幾乎相同,上面的第 1 步執行時間更快一些。

所以最后它還給你。
在您當前正在構建的系統中,您真正需要什么?
保留 $user->posts 添加新帖子,選擇第一個。
但是如果你只是想直接捕獲 $userPost,那么使用第二個選項。

注意:如果您已經知道用戶 $id 存在,則無需使用$user = User::find($id)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM