首页 文章

使用Laravel Eloquent中的“With()”函数获取特定列

提问于
浏览
116

我有两个表, UserPost . 一个 User 可以有多个 posts ,一个 post 只属于一个 user .

在我的 User 模型中,我有 hasMany 关系......

public function post(){
    return $this->hasmany('post');
}

在我的 post 模型中,我有 belongsTo 关系......

public function user(){
    return $this->belongsTo('user');
}

现在我想使用 Eloquent with() 加入这两个表,但是需要第二个表中的特定列 . 我知道我可以使用查询生成器,但我不想这样做 .

当我在 Post 模型中写道时......

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

它运行以下查询...

select * from `posts`
select * from `users` where `users`.`id` in (<1>, <2>)

但我想要的是......

select * from `posts`
select id,username from `users` where `users`.`id` in (<1>, <2>)

当我用...

Post::with('user')->get(array('columns'....));

它只返回第一个表中的列 . 我想要使用第二个表中的 with() 特定列 . 我怎样才能做到这一点?

8 回答

  • 3

    现在,您可以在 Collection 实例上使用 pluck 方法:

    这将只返回 Post modeluuid 属性

    App\Models\User::find(2)->posts->pluck('uuid')
    => Illuminate\Support\Collection {#983
         all: [
           "1",
           "2",
           "3",
         ],
       }
    
  • 233

    请注意,如果您只需要表中的一列,那么使用'lists'非常好 . 在我的情况下,我正在检索用户最喜欢的文章,但我只想要文章ID:

    $favourites = $user->favourites->lists('id');
    

    返回一个id数组,例如:

    Array
    (
        [0] => 3
        [1] => 7
        [2] => 8
    )
    
  • 59

    好吧,我找到了解决方案 . 它可以通过在 with() 中传递 closure 函数作为数组的第二个索引来完成

    Post::with(array('user'=>function($query){
            $query->select('id','username');
        }))->get();
    

    它只会从其他表中选择 idusername . 我希望这会有助于其他人 .


    请记住,在$ query-> select()中必须使用主键(在本例中为id)来实际检索必要的结果 . *

  • 11

    在你的 Post 模型中

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

    最初的功劳归于Laravel Eager Loading - Load only specific columns

  • 31

    走另一条路(hasMany):

    User::with(array('post'=>function($query){
            $query->select('id','user_id');
        }))->get();
    

    不要忘记包含外键(假设在此示例中为user_id)来解析关系,否则您的关系将得到零结果 .

  • 14

    你可以在Laravel 5.5中这样做:

    Post::with('user:id,username')->get();
    

    关注docs中所述的 id 字段:

    使用此功能时,应始终在要检索的列列表中包含id列 .

  • 0

    在Laravel 5.6中,您可以像这样调用特定字段

    $users = App\Book::with('author:id,name')->get();
    
  • 44

    在您的 Post 模型中:

    public function userWithName()
    {
        return $this->belongsTo('User')->select(array('id', 'first_name', 'last_name'));
    }
    

    现在你可以使用 $post->userWithName

相关问题