php - 在 Eloquent 模型类而不是 querybuilder 中指定选定的列
问题描述
每当我使用 eloquent 模型时,它都会选择 *,除非我在 querybuilder 对象中指定它。但是,我想在类中指定允许的字段。这对于确保正确的用户级别获得他们有权获得的详细信息很有用,因此它的属性与类一起存在。
我希望能够将其作为成员变量来执行,例如 $with:
/**
* @property mixed id
*/
class Attribute extends Model
{
protected $fillable = ["id", "business_id", "attribute_name"];
protected $with = ["attributeDetail", "business"];
protected $selectedFieldsThatMeanSelectStarDoesntHappen = ["id", "business_id", "attribute_name"];
}
因此,任何使用上述类的查询都会SELECT id, business_id, attribute_name
在使用该类时执行,而不是SELECT *
.
是否存在上述功能?我能得到的最接近的是全局范围:
class Attribute extends Model
{
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::addGlobalScope('selectFields', function (Builder $builder) {
$builder->select("id", "business_id", "attribute_name");
});
}
}
解决方案
你可以试试:创建一个新的构建器和一个特征来使用这个新的构建器:
class BuilderWithSpecifiedColumns extends Builder
{
public $selectedColumns = [];
public function __construct(ConnectionInterface $connection, Grammar $grammar = null, Processor $processor = null, array $selectedColumns = ['*'])
{
parent::__construct($connection, $grammar, $processor);
$this->selectedColumns = $selectedColumns;
}
/**
* @param string[] $columns
* @return \Illuminate\Support\Collection
*/
public function get($columns = ['*'])
{
return parent::get($this->selectedColumns ? $this->selectedColumns : $columns);
}
}
trait HasSelectedColumns
{
protected function newBaseQueryBuilder()
{
$connection = $this->getConnection();
return new BuilderWithSpecifiedColumns(
$connection,
$connection->getQueryGrammar(),
$connection->getPostProcessor(),
$this->selectedFieldsThatMeanSelectStarDoesntHappen,
);
}
}
使用上述特征
/**
* @property mixed id
*/
class Attribute extends Model
{
use HasSelectedColumns;
protected $fillable = ["id", "business_id", "attribute_name"];
protected $with = ["attributeDetail", "business"];
protected $selectedFieldsThatMeanSelectStarDoesntHappen = ["id", "business_id", "attribute_name"];
}
推荐阅读
- c# - 左右移动图片框
- groovy - 从字符串值提取构建的映射 - 无法恢复值
- angular - 使 mat-radio-button 成为表单中的必填字段
- javascript - 输入/更改/按键/焦点事件未触发
- c# - 我如何在 c# 中将波形文件转换为等效的数据数组
- javascript - 如何从销售订单打印 POS 收据?
- javascript - 如何从 RxJs 中的 flatMap 返回附加值
- java - ElasticSearch - 模糊查询 Java API 响应与 matchQuery 几乎相同
- ansible - “msg”:“未安装 winrm 或请求:没有名为 xmltodict 的模块”
- c# - ASP.NET MVC 5 API 应用程序使用自己的连接字符串而不是引用的应用程序连接字符串