2

I want get types only where wef is equal to current table wef. how to achieve this i am not able to get wef attribute with $this->attributes['wef']. Thanks in advance.

class Gst extends Model
    {
        //
        use Traits\UserAutoUpdate;
        protected $connection = 'mysql';
        protected $table = "gst";
        protected $fillable = ['name','wef'];

        public function types(){
           return $this->hasMany(GstType::class,'gst_id','id')->where('wef', $this->attributes['wef']);
        }   


    }

Error : "Undefined index: wef"

Neha
  • 2,136
  • 5
  • 21
  • 50

1 Answers1

2

You need a function that defines the relationship between GstType and Gst:

public function gstTypes()
{
     return $builder->hasMany(GstType::class,'gst_id','id');
}

Then make a scoped function:

public function scopeTypes($builder){
    return $builder->whereHas('gstTypes', function ($query) {
       $query->where('wef', $this->getAttribute('wef'));
   });
}   

And use it like:

 $types = GstType::types();
Brian Lee
  • 17,904
  • 3
  • 41
  • 52
  • The scope won't really work. In most query contexts, you won't have any attributes available, you'd have to fetch a model then query again on that model. Doesn't really seem like the right way to do it. – Devon Bessemer Sep 11 '18 at 11:37
  • Right, but where is the attribute 'wef' supposed to come from? – Devon Bessemer Sep 11 '18 at 14:44