在 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");

        });

    }

}


小唯快跑啊
浏览 92回答 1
1回答

精慕HU

您可以尝试一下:创建一个新的构建器和一个使用这个新构建器的特征: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"];}
打开App,查看更多内容
随时随地看视频慕课网APP