每当我使用 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");
});
}
}
精慕HU