当使用Laravel的Eloquent ORM时,我似乎无法动态地在我的模型上设置$ hidden和$ visible属性。
示例1:这有效:
class User extends Eloquent {
$this->visible = array('field_name');
function read()
{
return User::all();
}
}
示例2:动态设置Eloquent类的visible属性不起作用:
class User extends Eloquent {
function read($visible = array('field_name'))
{
$this->visible = $visible; // Also tried: $this->setVisible($visible);
return User::all();
}
}
示例3:适用于模型本身的解决方案,但不适用于急切加载的模型:
class User extends Eloquent {
function read($visible = array('field_name'))
{
$users = User::all();
return $users->get()->each(function($row) use ($visible) {
$row->setVisible($visible);
});
}
}
为了在Eagerly Loaded Models上动态设置$ visible属性,我没有看到另一个解决方案,而不是让示例2工作。但是如何?
答案 0 :(得分:2)
这是我为此目的而发明的:
use Illuminate\Database\Eloquent\Model;
/*
* trait allows to use a single method:
* getSerialized
* this function works as the following method:
* Illuminate\Database\Query\Builder::get(),
* and also returns the collection
* but accepts a parameter of an array type
* like that
* $records = Table1::getSerialized([
* 'appends' => ['calc_field1', 'calc_field2'],
* 'hidden' => ['field1', 'field2', 'field3'],
* 'visible' => ['id', 'name', 'calc_field1', 'calc_field2'],
* ]);
*
* the returned collection accords with params
* read more in Laravel documentation
* https://laravel.com/docs/5.1/eloquent-serialization
*/
trait Serialization
{
// scope filters ---------------------------------------------------------
private static $staticAppends;
private static $staticHidden;
private static $staticVisible;
public function __construct(array $attributes = []){
parent::__construct($attributes);
if (isset(self::$staticAppends)){
$this->appends = self::$staticAppends;
}
if (isset(self::$staticHidden)){
$this->hidden = self::$staticHidden;
}
if (isset(self::$staticVisible)){
$this->visible = self::$staticVisible;
}
}
public function scopeGetSerialized($query, array $params){
if (isset(self::$staticAppends)){
$staticAppends = self::$staticAppends;
} else {
$staticAppends = [];
}
if (isset(self::$staticHidden)){
$staticHidden = self::$staticHidden;
} else {
$staticHidden = [];
}
if (isset(self::$staticVisible)){
$staticVisible = self::$staticVisible;
}else {
$staticVisible = [];
}
if (isset($params['appends'])){
self::$staticAppends = $params['appends'];
}
if (isset($params['hidden'])){
self::$staticHidden = $params['hidden'];
}
if (isset($params['visible'])){
self::$staticVisible = $params['visible'];
}
$res = $query->get();
self::$staticAppends = $staticAppends;
self::$staticHidden = $staticHidden;
self::$staticVisible = $staticVisible;
return $res;
}
}
答案 1 :(得分:1)
由于$visible
是在实例级别上设置的(即它不是同一类型的所有模型之间共享的静态变量),否则没有更好的方法。