Mohib
Mohib

Reputation: 175

How to Retrieve data form many to many relation in laravel4?

Business Modal

class Business extends \Eloquent implements UserInterface, RemindableInterface{

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

Service Modal

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 retrieve the services of a business by the tag id. So how can i do it ????

Upvotes: 3

Views: 63

Answers (1)

chanafdo
chanafdo

Reputation: 5124

Try this.

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()

Upvotes: 1

Related Questions