在Laravel Eloquent中使用"With()"函数获取特定列 [英] Get Specific Columns Using “With()” Function in Laravel Eloquent

查看:451
本文介绍了在Laravel Eloquent中使用"With()"函数获取特定列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two tables, User and Post. One User can have many posts and one post belongs to only one user.

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

In my User model I have a hasMany relation...

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

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

And in my post model I have a belongsTo relation...

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

现在,我想使用Eloquent with()联接这两个表,但希望第二个表中有特定的列.我知道我可以使用查询生成器,但我不想这样做.

Now I want to join these two tables using Eloquent with() but want specific columns from the second table. I know I can use the Query Builder but I don't want to.

Post模型中,我写...

When in the Post model I write...

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

它运行以下查询...

It runs the following queries...

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

但是我想要的是...

But what I want is...

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

当我使用...

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

它仅返回第一个表中的列.我想要第二张表中使用with()的特定列.我该怎么办?

It only returns the column from the first table. I want specific columns using with() from the second table. How can I do that?

推荐答案

好,我找到了解决方案.可以通过在with()中将closure函数作为数组的第二个索引(如

Well I found the solution. It can be done one by passing a closure function in with() as second index of array like

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

它将仅从其他表中选择idusername.我希望这会对其他人有所帮助.

It will only select id and username from other table. I hope this will help others.

请记住,主键(在这种情况下为id)必须是 $ query-> select()实际检索必要的结果.*

Remember that the primary key (id in this case) needs to be the first param in the $query->select() to actually retrieve the necessary results.*

这篇关于在Laravel Eloquent中使用"With()"函数获取特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆