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"

6
  • I don't think $this->attributes['wef'] will work. You need to pass the value in argument of types() function. Commented Sep 11, 2018 at 10:42
  • if you are using eager loading.. to get attributes just $this->wef Commented Sep 11, 2018 at 11:18
  • possible duplicate of stackoverflow.com/questions/18520209/… Commented Sep 11, 2018 at 11:35
  • @Neha is it working? Commented Sep 11, 2018 at 13:16
  • 1
    as @DigitalDrifter answer.. better do like suggested. Commented Sep 12, 2018 at 6:08

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Right, but where is the attribute 'wef' supposed to come from?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.