Laravel/Eloquent - 渴望加载隐藏/可见属性

Ron*_*hof 8 php laravel eloquent

当使用Laravel的Eloquent ORM时,我似乎无法动态地在我的模型上设置$ hidden和$ visible属性.

示例1:这有效:

class User extends Eloquent {
   $this->visible = array('field_name');

   function read() 
   {
      return User::all();
   }
}
Run Code Online (Sandbox Code Playgroud)

示例2:动态设置Eloquent类的visible属性不起作用:

class User extends Eloquent {
   function read($visible = array('field_name'))
   {
      $this->visible = $visible; // Also tried: $this->setVisible($visible);

      return User::all();
   }
}
Run Code Online (Sandbox Code Playgroud)

示例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);
      });
   }
}
Run Code Online (Sandbox Code Playgroud)

为了在Eagerly Loaded模型上动态设置$ visible属性,我没有看到另一个解决方案,而不是让示例2工作.但是怎么样?

And*_*eas 2

正如$visible在实例级别上设置的那样(即它不是在同一类型的所有模型之间共享的静态变量),不 - 没有更好的方法来做到这一点。