亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Eloquent 模型類而不是 querybuilder 中指定選定的列

在 Eloquent 模型類而不是 querybuilder 中指定選定的列

PHP
小唯快跑啊 2023-09-22 16:13:44
每當我使用 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");        });    }}
查看完整描述

1 回答

?
精慕HU

TA貢獻1845條經驗 獲得超8個贊

您可以嘗試一下:創建一個新的構建器和一個使用這個新構建器的特征:


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

}


查看完整回答
反對 回復 2023-09-22
  • 1 回答
  • 0 關注
  • 126 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號