最新下载
热门教程
- 1
 - 2
 - 3
 - 4
 - 5
 - 6
 - 7
 - 8
 - 9
 - 10
 
Laravel Eloquent下with() 函数只返回指定列
时间:2022-06-25 00:40:20 编辑:袖梨 来源:一聚教程网
假如我们现在有两张表:user 和 posts,每个 User 可以拥有多个 Posts,而每一篇 Post 只能属于一个 User。下面分别是 User Model 和 Post Model 中定义的关系:
// User.php 
public function post(){
    return $this->hasMany('post');
}
 
 
// Post.php
public 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 (<1>,<2>)
但是我们可能并不需要 User 表中所有的字段,例如我们只需要 id 和 username 两个字段:
select * from `posts`
select id,username from `users` where `users`.`id` in (<1>,<2>)
我们可以通过下面两种方法来实现。
方法一:在 with() 中指定
Post::with(array('user'=>function($query){
    $query->select('id','username');
}))->get();
方法二:修改 Model 文件
修改 Post.php 文件中 user() 方法:
public function user()
{
    return $this->belongsTo('User')->select(array('id', 'username'));
}
相关文章
- 我的世界灾厄巡逻队怎么解决 灾厄巡逻队机制详解 11-04
 - 【精选】圣诞节朋友圈最调皮的文案精彩句子汇编115句 11-04
 - 我的世界袭击(Raid)怎么玩 mc袭击机制介绍 11-04
 - 我的世界wiki官网入口 国际与中文站点使用指南 11-04
 - 我的世界Java版最新更新内容是什么 1.21.9正式版内容汇总 11-04
 - 逃离鸭科夫农场镇嫌疑人任务怎么做 嫌疑人任务流程 11-04