首页 > 解决方案 > 在 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");
        });
    }
}

标签: phplaraveleloquent

解决方案


你可以试试:创建一个新的构建器和一个特征来使用这个新的构建器:

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"];
}

推荐阅读