Select Eloquent 预加载中的特定字段不起作用
Select specific fields in Eloquent eager loading not working
我有一个 Notifications
模型属于 User
。我想在通知集合被 selected 时加载用户,并且只加载带有 names
和 emails
的模型。但是,当使用 select 方法时,查询 returns null.
$notifications->load(['user' => function($query){
$query->select(["name","email"]);
}]);
如果select()
方法的参数如下所示,它会给出所有字段:
$notifications->load(['user' => function($query){
$query->select(["*"]
}]);
也许 select像这样处理字段:
$notifications->load('user:id,name,email');
您尝试的目的是添加约束,而不是 select 某些字段
只需要添加主键列就可以了。
$notifications->load(['user' => function($query){
$query->select(["ID","name","email"]);
}]);
这样任何约束都可以添加到查询中。
如果使用 select 获取数据,则必须通过 foreign_key。
看看
public function index()
{
$employee = Employee::with(['pay_salary' => function($query){
$query->select(['employee_id','salary_amount'])
->whereMonth('paying_date',\Carbon\Carbon::now()->month);
},'getSalary:id,employeeID,salary'])->get();
return View::make('admin.salary.index',['data' => $employee]);
}
我有一个 Notifications
模型属于 User
。我想在通知集合被 selected 时加载用户,并且只加载带有 names
和 emails
的模型。但是,当使用 select 方法时,查询 returns null.
$notifications->load(['user' => function($query){
$query->select(["name","email"]);
}]);
如果select()
方法的参数如下所示,它会给出所有字段:
$notifications->load(['user' => function($query){
$query->select(["*"]
}]);
也许 select像这样处理字段:
$notifications->load('user:id,name,email');
您尝试的目的是添加约束,而不是 select 某些字段
只需要添加主键列就可以了。
$notifications->load(['user' => function($query){
$query->select(["ID","name","email"]);
}]);
这样任何约束都可以添加到查询中。
如果使用 select 获取数据,则必须通过 foreign_key。 看看
public function index()
{
$employee = Employee::with(['pay_salary' => function($query){
$query->select(['employee_id','salary_amount'])
->whereMonth('paying_date',\Carbon\Carbon::now()->month);
},'getSalary:id,employeeID,salary'])->get();
return View::make('admin.salary.index',['data' => $employee]);
}