I have four Models:
- User
- Customer
- Score
- Opportunity
Relations are defined as such:
- HasMany Client user
- HasMany Store Client
- HasMany Opportunity Store
- HasManyThrough Store user, Client (this works)
The problem is that I am trying to access the User-> Opportunity relationships through Laravel's built-in relationships, but it seems to me that I cannot do this without a special query or an extra column of user_id table capabilities to provide direct access (although it can be concluded from the relationship Store-> Client). I'm also not a fan of nested loops foreachif they can be avoided.
My question is:
? :
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(){
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(){
return $this->opportunities()->get();
}
}
Client
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');
}
}