沃梦达 / 编程问答 / php问题 / 正文

Laravel/Eloquent - 急切加载隐藏/可见属性

Laravel/Eloquent - Eager loaded hidden/visible properties(Laravel/Eloquent - 急切加载隐藏/可见属性)

本文介绍了Laravel/Eloquent - 急切加载隐藏/可见属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When using Laravel's Eloquent ORM, I can't seem to set the $hidden and $visible properties on my Model dynamically.

示例 1:这有效:

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

   function read() 
   {
      return User::all();
   }
}

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

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 工作之外,我没有看到其他解决方案.但是如何?

In order to set the $visible property dynamically on Eagerly Loaded Models, I don't see another solution than to get Example 2 to work. But how?

推荐答案

由于 $visible 是在实例级别设置的(即它不是在同一类型的所有模型之间共享的静态变量),不 - 没有更好的方法可以做到这一点.

As $visible is set on an instance level (i.e. it's not a static variable shared between all models of the same type), no - there's no better way to do this.

这篇关于Laravel/Eloquent - 急切加载隐藏/可见属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Laravel/Eloquent - 急切加载隐藏/可见属性

基础教程推荐