使用Eloquent的话,有两种方式:

1. 使用select()

$users = User::select(['name'])->get();

2. 直接将列名数组作为参数传入all()/get()/find()等方法中

1 $users = User::all(['name']);
2 $admin_users = User::where('role', 'admin')->get(['id', 'name']);
3 $user = User::find($user_id, ['name']);

 

在关联查询中使用同理:

$posts = User::find($user_id)->posts()->select(['title'])->get();
$posts = User::find($user_id)->posts()->get(['title', 'description']);

注意这里不能使用动态属性(->posts)来调用关联关系,而需要使用关联关系方法(->posts())。

相关文章:

  • 2022-12-23
  • 2021-09-04
  • 2022-12-23
  • 2021-09-08
  • 2021-09-21
  • 2022-12-23
  • 2022-03-03
  • 1970-01-01
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-14
相关资源
相似解决方案