Solivan
Solivan

Reputation: 735

hasMany for one table and return Main model collection laravel

hi and thanks for answer. there is fields table. each field has many related fields that save in related_fields table. so related_fields table has tow columns:

field_id, related_field

I use this code for get related_fields:

    public function linked(){
    return $this->hasMany('App\RelatedField','field_id','related_field');
}

but the problem is that this function returns RelatedField collection as result not Fields collection and that is not needed and Fields collection is needed. what is the best way to resolve this problem?

Upvotes: 1

Views: 146

Answers (1)

Brian Lee
Brian Lee

Reputation: 18187

Try using a HasManyThrough relationship. Add a fields method on the Field model:

// Field.php
public function fields()
{
    return $this->hasManyThrough(App\Field::class, App\RelatedField::class, 'field_id', 'id');
}

Upvotes: 1

Related Questions