[英]Cakephp's beforeSave() not retaining new data using $model::save()
[英]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);
我想在不對數據庫進行額外查詢的情況下訪問新的Post
的User
。 如果我執行以下操作,它將查詢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 和時間戳,無需重新加載所有帖子,為您節省一點性能和執行時間。
有人可能會問,執行了多少查詢?
我在事務之前使用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.