代码之家  ›  专栏  ›  技术社区  ›  Ali

without GlobalScope无法与Laravel模型中的hasMany相关联地工作

  •  0
  • Ali  · 技术社区  · 5 月前

    我的范围:

    <?php
    
    namespace App\Scopes;
    
    use Auth;
    use Illuminate\Database\Eloquent\Builder;
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\Scope;
    
    class InventorySeriesScope 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
         */
        // withoutGlobalScope(ClinicScope::class)
        public function apply(Builder $builder, Model $model)
        {
            $table = $model->getTable();
            $builder->where($table . '.is_used',0);
             
        }
    }
    
    

    使用范围的InventorySeries模型:

    <?php
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\SoftDeletes;
    use App\Scopes\InventorySeriesScope;
    
    class InventorySeries extends Model
    {
        use SoftDeletes;
    
        protected $table="inventory_series";
        protected $primarykey="id";
        protected $guarded=['id'];
    
        protected static function boot()
        {
            parent::boot();
            static::addGlobalScope(new InventorySeriesScope);
        }
    
    }
    
    

    我使用的模型 没有GlobalScope :

    <?php
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\SoftDeletes;
    
    class GatePassOutwardEntryChild extends Model
    {
        use SoftDeletes;
    
        protected $table = 'gatepass_outward_entry_child';
        protected $PrimaryKey = 'id';
        protected $guarded = ['id'];
    
        public function inventoryseries()
        {
            return $this->hasMany('App\Models\InventorySeries','gatepass_outward_child_id','id')->withoutGlobalScope(InventorySeriesScope::class);
        }
    }
    
    

    我想要数据的控制器 没有GlobalScope 它提供了包括全球范围在内的数据

    $data['child'] = GatePassOutwardEntryChild::with('inventoryseries')->get();
    dd($data['child'][0]);
    

    因此,我获得了以下数据 inventoryseries 具有 is_used 作为 0 但我有一些记录 已使用 作为 0 1. 两者都有,我想要所有的记录,而不仅仅是 0

    1 回复  |  直到 5 月前
        1
  •  1
  •   kunjal chandegara    5 月前

    在模型中给出完整路径,而不是使用类

    public function inventoryseries()
    {
       return $this->hasMany('App\Models\InventorySeries','gatepass_outward_child_id','id')->withoutGlobalScope("App\Scopes\InventorySeriesScope");
    
    }
    

    它对我有效!!