Php 过滤Laravel4中返回关系的字段?
在Laravel 4中使用“急加载”时,我们可以使用以下方式加载关系:Php 过滤Laravel4中返回关系的字段?,php,database,laravel,filtering,eager-loading,Php,Database,Laravel,Filtering,Eager Loading,在Laravel 4中使用“急加载”时,我们可以使用以下方式加载关系: $user = User::with('role')->find(1); 它将返回用户的表示,我们可以通过 $user->roles(); 现在,我们还可以使用where来过滤急切的加载 $user = User::with(array('role' => function($query) { $query->where('name', 'like', '%key%'); }))->
$user = User::with('role')->find(1);
它将返回用户的表示,我们可以通过
$user->roles();
现在,我们还可以使用where来过滤急切的加载
$user = User::with(array('role' => function($query) {
$query->where('name', 'like', '%key%');
}))->find(1);
仅当角色名称字段包含键
时,才会返回填充角色的用户表示
我们可以通过添加select()
约束来限制用户表示返回的字段
$user = User::with(array('role' => function($query) {
$query->where('name', 'like', '%key%');
}))->select('email')->find(1);
它将只返回用户表示上的电子邮件
和id
字段,但返回角色表示上的所有字段
我希望能够限制关系中返回的字段(用于api),但似乎找不到方法;我试过下面两种方法
$user = User::with(array('role' => function($query) {
$query->select('name');
}))->find(1);
及
可以在关系定义中指定所需的列
// app/model/User.php
<?php
class User extends Eloquent
{
public function roles()
{
return $this->hasMany('Role')->select(array('id', 'name'));
}
}
这应该是可行的。虽然它不过滤返回的列,但如果您不想获取相当大的列(例如博客文章内容),这不是一个可行的解决方案,它可以用于过滤表示为数组或Json时可见的列
//fetch the unfiltered relationship
$user = User::with('roles')->find($id);
//loop over each model in that relationship and set the visible properties
$user->roles->each(function($role){
$role->setVisible(['id', 'name', 'pivot']);
});
问题是,直到api用户在查询字符串中使用类似于
?fields=email,role:(name)
的内容请求时,我才知道我要查找哪些列。不,这不起作用,它确实会在角色表示中首先列出已命名的字段,但它不会将响应仅限于这些字段!
$user = User::with(array('role' => function($query) {
$query->select(array('id', 'name'));
}))->find(1);
//fetch the unfiltered relationship
$user = User::with('roles')->find($id);
//loop over each model in that relationship and set the visible properties
$user->roles->each(function($role){
$role->setVisible(['id', 'name', 'pivot']);
});