Reputation: 285
I am building an application in laravel in which each channel has some sections and you can post threads in the sections. I would like to access the channel from the thread. The hierarchy so far is this -channel --section ---threads
here are the three model classes
channel
use Illuminate\Database\Eloquent\Model;
class Channel extends Model
{
public function users(){
return $this->belongsToMany('App\User');
}
public function posts(){
return $this->hasMany('App\Post');
}
public function isSubscribed($id){
return $this->users()->find($id);
}
public function sections(){
return $this->hasMany('App\Section');
}
}
section
{
public function channel(){
return $this->belongsTo('App\Channel');
}
public function threads(){
return $this->hasMany('App\Thread');
}
}
thread
{
protected $fillable=['title','body','solved'];
public function solutions(){
return $this->hasMany('App\Solution');
}
public function comments(){
return $this->hasMany('App\ThreadComment');
}
public function section(){
return $this->belongsTo('App\Section');
}
public function arguments(){
return $this->belongsToMany('App\Argument');
}
public function user(){
return $this->belongsTo('App\User');
}
public function reports(){
return $this->morphTo('App\Report','reportable');
}
}
what I would like to do is to have a channel()
method in thread class that makes me access the channel without having to do $thread->section->channel
each time
Upvotes: 0
Views: 166
Reputation: 306
If you don't have a problem using a package for this, use https://github.com/staudenmeir/eloquent-has-many-deep. You can have any levels of relationships.
Read the usage section of the package for details.
Upvotes: 0
Reputation: 15786
If you really want to, use an accesor.
public function getChannelAttribute()
{
return $this->section->channel;
}
Upvotes: 1