<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Lib\Collection;
class Model extends EloquentModel
{
public function newCollection(array $models = [])
{
return new Collection( $models );
}
}
?>
其次,我创建了以下自定义收集类:
<?php
namespace Lib;
use Illuminate\Support\Collection as EloquentCollection;
class Collection extends EloquentCollection
{
public function extract()
{
$attributes = func_get_args();
return array_extract( $this->toArray(), $attributes );
}
}
?>
最后,所有的模型都应该扩展你的自定义模型,像这样:
<?php
namespace App\Models;
class Article extends Model
{
...
// get your main collection with all the attributes...
$users = Users::get();
// build your second collection with a subset of attributes. this new
// collection will be a collection of plain arrays, not Users models.
$subset = $users->map(function ($user) {
return collect($user->toArray())
->only(['id', 'name', 'email'])
->all();
});
将它们放在一起,您会得到“对于用户集合中的每个用户,返回一个只包含 id、 name 和 email 属性的数组”
Laravel 5.5更新
Laravel 5.5在 Model 上添加了一个 only方法,它基本上和 collect($user->toArray())->only([...])->all()做同样的事情,所以这可以在5.5 + 中稍微简化为:
// get your main collection with all the attributes...
$users = Users::get();
// build your second collection with a subset of attributes. this new
// collection will be a collection of plain arrays, not Users models.
$subset = $users->map(function ($user) {
return $user->only(['id', 'name', 'email']);
});
// get your main collection with all the attributes...
$users = Users::get();
// build your second collection with a subset of attributes. this new
// collection will be a collection of plain arrays, not Users models.
$subset = $users->map->only(['id', 'name', 'email']);
例如,假设您想要显示一个表单,用于在一个系统中创建一个新用户,在这个系统中 User 只有一个 Role,而且这个 Role 可以用于许多 User。
User 模型应该是这样的
class User extends Authenticatable
{
/**
* User attributes.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'role_id'
];
/**
* Role of the user
*
* @return \App\Role
*/
public function role()
{
return $this->belongsTo(Role::class);
}
...
和榜样
class Role extends Model
{
/**
* Role attributes.
*
* @var array
*/
protected $fillable = [
'name', 'description'
];
/**
* Users of the role
*
* @return void
*/
public function users()
{
return $this->hasMany(User::class);
}
}
如何只获得特定的属性?
在我们想要创建的特定表单中,您将需要“角色”中的数据,但实际上并不需要描述。
/**
* Create user
*
* @param \App\Role $model
* @return \Illuminate\View\View
*/
public function create(Role $role)
{
return view('users.create', ['roles' => $role->get(['id', 'name'])]);
}
Notice that we're using $role->get(['id', 'name']) to specify we don't want the description.