【问题标题】:how set fixed where query in model laravel如何在模型 laravel 中设置固定位置查询
【发布时间】:2022-01-22 18:06:24
【问题描述】:

我的网站有 5 种语言 已为名称为 language 的所有表添加一列

在数据库中使用select数据时,如何在表的模型中添加where('language' , App::getLocale())查询?

范围是一种解决方案,但另一种方式

感谢您的建议

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您可以添加全局作用域,并将作用域添加到模型的booted 方法中。

    ## App/Scopes/LanguageScope.php
    
    <?php
    
    namespace App\Scopes;
    
    use Illuminate\Database\Eloquent\Builder;
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\Scope;
    use Illuminate\Support\Facades\App;
    
    class LanguageScope implements Scope
    {
        /**
         * Apply the scope to a given Eloquent query builder.
         *
         * @param  \Illuminate\Database\Eloquent\Builder  $builder
         * @param  \Illuminate\Database\Eloquent\Model  $model
         * @return void
         */
        public function apply(Builder $builder, Model $model)
        {
            $builder->where('language', App::getLocale());
        }
    }
    

    在你的模型中。

    ## App/Models/YourModel.php
    <?php
    
    namespace App\Models;
    
    use App\Scopes\LanguageScope;
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
    
    class YourModel extends Model
    {
        use HasFactory;
    
        /**
         * The "booted" method of the model.
         *
         * @return void
         */
        protected static function booted()
        {
            static::addGlobalScope(new LanguageScope);
        }
    }
    

    因此,每当您查询记录时,where 条件将被自动添加。你可以阅读更多关于全局作用域here

    【讨论】:

      【解决方案2】:

      您可以覆盖您的语言模型 (app\Models\Language.php) 上的 newQuery() 函数

      /**
       * Get a new query builder for the model's table.
       *
       * @return \Illuminate\Database\Eloquent\Builder
       */
      public function newQuery()
      {
          return parent::newQuery()->where('language', App::getLocale());
      }
      

      【讨论】:

        猜你喜欢
        • 2018-05-28
        • 1970-01-01
        • 2016-06-19
        • 1970-01-01
        • 1970-01-01
        • 2015-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多