Laravel Eloquent: 如何仅从关联表中获取特定列?

108

我在Eloquent中有两个连接的表,分别是主题和用户。

主题模型:

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

用户模型:

public function themes() {
  return $this->has_many('Theme');
}

我的Eloquent api调用如下:

return Response::eloquent(Theme::with('user')->get());

使用如下代码可仅从用户模型中获取“username”列:
``` Theme.objects.values('user__username') ```
需要注意的是,“user”是外键字段名,应该根据具体情况进行调整。

我正在处理类似的任务,我想知道如果我使用“Response”,我需要导入哪种类? - Agnes Palit
16个回答

4
在 Laravel 5.5 中,最干净的方法是:
Theme::with('user:userid,name,address')->get()

您需要在冒号后面加上您想选择的字段,用逗号分隔,不要在它们之间留空格。

你知道在使用分页时如何获取相关表的特定列吗? - Daniyal Nasir
@Kamlesh,如果您在Theme表上不指定select()语句,则会获取所有字段。 - JoeGalind
谢谢您的回复。但我认为您没有理解我的要求,即“我想获取第一个表的所有字段,并且还想获取一些连接表的字段”,正如我在上一条评论中所述。再次感谢。 - Kamlesh
所以我猜你想要两个表格?那么可以这样写:Theme::with(['user:userid,name,address', 'table2'])->get()这将获取主题表的所有字段,table2的所有字段以及用户的一些字段。 - JoeGalind

4

2

使用模型:

Model::where('column','value')->get(['column1','column2','column3',...]);

使用查询构建器:

DB::table('table_name')->where('column','value')->get(['column1','column2','column3',...]);

0

如果我理解正确,返回的内容是可以接受的,除非你只想看到一列。如果是这样,下面的代码应该更简单:

return Response::eloquent(Theme::with('user')->get(['username']));

0

#你可以从两个或三个不同的表中获取选定的列

$users= DB::Table('profiles')->select('users.name','users.status','users.avatar','users.phone','profiles.user_id','profiles.full_name','profiles.email','profiles.experience','profiles.gender','profiles.profession','profiles.dob',)->join('users','profiles.user_id','=','users.id')
            ->paginate(10);

-3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接