我有两个表,User和Post。一个用户可以有多个帖子,一个帖子只能属于一个用户。

在我的用户模型中,我有一个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()的特定列。我该怎么做呢?


当前回答

还有另一种方法可以加载特定的列

public function show(Post $post)
{
    $posts = $post->has('user')->with('user:id,name,email,picture')->findOrFail($post->id);
    return view('your_blade_file_path',compact('posts);
}

在Post模型中,你也应该有用户关系

public function user()
{
    return $this->belongsTo( User::class, 'user_id')->withDefault();
}

注意:Laravel文档中提到了它。

https://laravel.com/docs/8.x/eloquent-relationships#eager-loading-specific-columns

其他回答

您可以试试这段代码。在laravel 6版本中进行了测试。

Controller code
 public function getSection(Request $request)
{

  Section::with(['sectionType' => function($q) {
      $q->select('id', 'name');
  }])->where('position',1)->orderBy('serial_no', 'asc')->get(['id','name','','description']);
  return response()->json($getSection);
}
Model code
public function sectionType(){
    return $this->belongsTo(Section_Type::class, 'type_id');
}

所以,类似于其他的解决方案是我的:

// For example you have this relation defined with "user()" method
public function user()
{
    return $this->belongsTo('User');
}
// Just make another one defined with "user_frontend()" method
public function user_frontend()
{
    return $this->belongsTo('User')->select(array('id', 'username'));
}

// Then use it later like this
$thing = new Thing();
$thing->with('user_frontend');

// This way, you get only id and username, 
// and if you want all fields you can do this

$thing = new Thing();
$thing->with('user');

您还可以在访问相关模型时指定该模型的列。

::第一()- >用户()- >((“列…”));

我找到解决办法了。它可以通过将一个闭包函数作为数组的第二个索引来实现

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

它将只从其他表中选择id和用户名。我希望这能帮助到其他人。


方法中的第一个参数是主键(在本例中是id) $query->select()实际检索必要的结果

还有另一种方法可以加载特定的列

public function show(Post $post)
{
    $posts = $post->has('user')->with('user:id,name,email,picture')->findOrFail($post->id);
    return view('your_blade_file_path',compact('posts);
}

在Post模型中,你也应该有用户关系

public function user()
{
    return $this->belongsTo( User::class, 'user_id')->withDefault();
}

注意:Laravel文档中提到了它。

https://laravel.com/docs/8.x/eloquent-relationships#eager-loading-specific-columns