如何在laravel4中从多对多关系中检索数据?

时间:2015-06-08 05:05:55

标签: php mysql laravel-4 eloquent

商业模式

class Business extends \Eloquent implements UserInterface, RemindableInterface{

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

服务模式

class Service extends \Eloquent {


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


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

标签模式

class Tag extends \Eloquent {

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

现在我想通过标签ID检索企业的服务。 那我该怎么办呢?

1 个答案:

答案 0 :(得分:1)

试试这个。

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

编辑:更改了答案。 上一个答案:

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