【发布时间】:2014-11-14 07:03:41
【问题描述】:
我有四个模型:
- 用户
- 客户
- 商店
- 机会
关系是这样定义的:
- 用户有很多客户
- Client hasMany Store
- 商店有很多机会
- 用户 hasManyThrough Store,客户端(此工作)
问题是我试图通过内置的 Laravel 关系访问 User->Opportunity 关系,但如果没有自定义查询或机会上的附加 user_id 列,我似乎无法做到这一点表以允许直接访问(即使可以从 Store->Client 关系中推断出一个)。如果可以避免嵌套 foreach 循环,我也不喜欢它们。
我的问题:
在这种情况下,有没有办法更深入并直接访问用户的机会?实际Model代码及所有相关关系如下:
用户
class User extends Eloquent{
public function clients(){
return $this->hasMany('Client');
}
public function stores(){
return $this->hasManyThrough('Store', 'Client');
}
public function proposals(){
return $this->hasMany('Proposal');
}
public function opportunities(){ //This does the job, but I feel like it could be better
return Opportunity::join('stores', 'stores.id', '=', 'opportunities.store_id')->
join('clients', 'clients.id', '=', 'stores.client_id')->
join('users', 'users.id', '=', 'clients.user_id')->
select('opportunities.*')->
where('users.id', $this->id);
}
public function getOpportunitiesAttribute(){ //This just helps mimic the hasManyThrough shorthand
return $this->opportunities()->get();
}
}
客户
class Client extends Eloquent{
public function stores(){
return $this->hasMany('Store');
}
public function user(){
return $this->belongsTo('User');
}
public function opportunities(){
return $this->hasManyThrough('Opportunity', 'Store');
}
}
商店
class Store extends Eloquent {
public function client(){
return $this->belongsTo('Client');
}
public function opportunities(){
return $this->hasMany('Opportunity');
}
}
机会
class Opportunity extends Eloquent {
public function store(){
return $this->belongsTo('Store');
}
}
【问题讨论】:
-
我不了解 Laravell,但根据我的 Java Persistance API 经验,我可以说您需要针对此类问题的自定义查询,或者,正如您所提到的,用户和机会之间的直接关系。
-
@ITroubs 是的,这就是它目前的样子。不过,如果我能把蛋糕也吃掉,那就太棒了。
-
您使用
joins的解决方案几乎是您能做的最好的。否则,您可以为这种情况创建自定义关系,这将像hasManyThorugh一样工作,但嵌套级别多了 1 个。 -
像你一样使用连接也是我处理远距离关系的方式。还没有找到另一种方法,但应该可以通过以类似于
hasManyThrough()的方式创建关系来实现。这个包做belongsToThrough()并管理多个级别,所以可以作为灵感:github.com/znck/belongs-to-through
标签: php mysql laravel eloquent has-many-through