
[英]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.