How to get data from many relationships many in laravel4?

Business modal

class Business extends \Eloquent implements UserInterface, RemindableInterface{

    public function services()
    {
        return $this->hasMany('Services');
    }
}

      

Service modification

class Service extends \Eloquent {


    public function business()
    {
        return $this->belongsTo('Business');
    }


    public function tag()
    {
        return $this->belongsToMany('Tag','service_tags','service_id','tag_id');
    }
}

      

Tag Modal

class Tag extends \Eloquent {

    public function service()
    {
        return $this->belongsToMany('Service','service_tags','service_id','tag_id');
    }
} 

      

Now I want to get business services by tag id. So how can I do this ????

+3


source to share


1 answer


Try it.

Service::whereHas('tag', function($query) use ($tagId) {
    $query->where('tag_id', '=', $tagId);
})->get();

      



Edit: changed the answer. Previous answer:

Business::with(['services')->whereHas('tag', function($query) use ($tagId) {
    $query->where('tag_id', '=', $tagId);
})->get()

      

+1


source







All Articles