• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Laravel Eloquent 中 with() 函数只返回指定列

php 搞代码 3年前 (2022-01-23) 12次浏览 已收录 0个评论
文章目录[隐藏]

Laravel 提供了 Eager Loading使用 with()方法来缓解 N+1 的问题,但是在实际使用中还是存在一些问题的, with()会直接查询出表中所有的字段,而我们可能仅仅需要其中指定的某几个字段。

假如我们现在有两张表: user和 posts,每个 User 可以拥有多个 Posts,而每一篇 Post 只能属于一个 User。下面分别是 User Model 和 Post Model 中定义的关系:

// User.php public function post(){    return $this->hasMany('post');}// Post.phppublic function user(){    return $this->belongsTo('user');}

通过 with()方法,我们可以这样获取所有的 Posts 并同时查出对应的 User 信息,可以使用这样的方法:

public function getAllPosts() {    return Post::with('user')->get();}

这实际上会执行下面两句 SQL 语句:

select * from `posts`select * from `users` where `users`.`id` in (, )

但是我们可能并不需要 User 表中所有的字段,例如我们只需要 id和 username两个字段:

select * from `posts`select id,username from `users` where `users`.`id` in (, )

我们可以通过下面两种方法来实现。

方法一:在 with() 中指定

Post::with<i style="color:transparent">本文来源gaodai$ma#com搞$$代**码)网8</i><strong>搞代gaodaima码</strong>(array('user'=>function($query){    $query->select('id','username');}))->get();

方法二:修改 Model 文件

修改 Post.php 文件中 user() 方法:

public function user(){    return $this->belongsTo('User')->select(array('id', 'username'));}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Laravel Eloquent 中 with() 函数只返回指定列
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址