[英]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);
I want to access the new Post
's User
without making an additional query to the database.我想在不对数据库进行额外查询的情况下访问新的Post
的User
。 It queries the database for the User
if I do the following:如果我执行以下操作,它将查询User
的数据库:
$userPost = $post->user;
I'm aware I could just do $userPost = $user
, but for certain reasons, I don't want to do it that way.我知道我可以只做$userPost = $user
,但出于某些原因,我不想那样做。
So my question is, would it be possible to eager load the User
when saving the new Post
with save()
?所以我的问题是,在使用save()
新Post
时是否可以预先加载User
?
I just try the following way to save new post with minimal query.我只是尝试以下方式以最少的查询保存新帖子。
$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);
The new Post is there with id and timestamps, without need to reload all posts, saving you a bit performance and execution time.新的 Post 有 id 和时间戳,无需重新加载所有帖子,为您节省一点性能和执行时间。
One might asked, how many queries were executed?有人可能会问,执行了多少查询?
I used DB::enableQueryLog()
before transactions and DB::getQueryLog()
after transactions to track these queries.我在事务之前使用DB::enableQueryLog()
并在事务之后使用DB::getQueryLog()
来跟踪这些查询。
... ...
And regarding your question: $post->user
.关于你的问题: $post->user
。
Unfortunately this will still trigger an extra query .不幸的是,这仍然会触发额外的查询。
"select * from "users" where "users"."id" = 1 limit 1"
Now lets compare to good old add post to user steps.现在让我们比较好旧的向用户添加帖子的步骤。 (2nd option) (第二个选项)
$id = 1;
$user = User::with('posts')->find($id); // needs 2 queries
$post = Post::create(['user_id' => $id, 'title'.... ]); // 3rd query
$user->load('posts');
// 4th query (but this is optional) // 第 4 个查询(但这是可选的)$userPost = $post->user; // and last query
In total will need to execute 4 or 5 queries, depend on do you need to load all posts as user's children.总共需要执行 4 或 5 个查询,具体取决于您是否需要将所有帖子加载为用户的孩子。
In term of performance, cpu usage and execution time are almost the same, with the 1st steps above is a bit faster in execution time.在性能方面,cpu 使用率和执行时间几乎相同,上面的第 1 步执行时间更快一些。
So at the end it is back to you.所以最后它还给你。
What do you really need in the system you are currently building?在您当前正在构建的系统中,您真正需要什么?
Keep the $user->posts with new post added, that choose 1st.保留 $user->posts 添加新帖子,选择第一个。
But if you just want directly to catch $userPost, than use 2nd option.但是如果你只是想直接捕获 $userPost,那么使用第二个选项。
Note: no need to use $user = User::find($id)
if you already know that user $id is exists.注意:如果您已经知道用户 $id 存在,则无需使用$user = User::find($id)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.