【问题标题】:How to Retrieve data form many to many relation in laravel4?如何在 laravel 4 中从多对多关系中检索数据?
【发布时间】:2015-06-08 05:05:54
【问题描述】:

商业模式

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 检索企业的服务。 那我该怎么办????

【问题讨论】:

  • 您能否详细解释一下您的问题,您想要通过标签 id 的企业还是具有特定标签 id 的企业服务?
  • 实际上我有业务和该业务的所有服务。现在我想按标签对服务进行排序
  • 如果你这么问,那么你的问题是错误的,请修改。我已经更新了我的答案。

标签: php mysql laravel-4 eloquent


【解决方案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()

【讨论】:

  • 调用未定义的方法 Illuminate\Database\Query\Builder::tag() 发生。我现在该怎么办
  • 如果我这样写 $business->service->whereHas('tag', function($query) use ($tagId) { $query->where('tag_id', '=' , $tagId); })->get();它会工作
  • 你可以试试看。但是使用$business->service() 而不是$business->service(带括号)
  • 试试这个。如果您需要业务服务。未测试。 Business::with(['service' => funciton($query) { $query->whereHas('tag', function($query) use ($tagId) { $query->where('tag_id', '=', $tagId); }) }])->get();
  • 由于一些语法错误,我无法正常工作。老兄,你能告诉我逻辑,以便我自己做
猜你喜欢
  • 2014-08-11
  • 2017-01-17
  • 1970-01-01
  • 2013-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多