rusyko
rusyko

Reputation: 29

Laravel eloquent how to dynamically create relations?

I need to dynamically create different relationships (oneToOne, manyToMany, oneToMany) for my model with different tables and foreign keys and then retrieve my model with all this relations. Is there any way to do so? For example, instead of doing something like this:

public function relOne()
{
    return $this->hasMany('one', 'foreign_one', 'one');
}
        
public function relTwo()
{
    return $this->hasMany('two', 'foreign_two', 'two');
}

I need to do something like this:

$model->createRelation('relOne', function ($model) {
    return $model->hasMany('one', 'foreign_one', 'one');
});

$model->createRelation('relTwo', function ($model) {
     return $model->hasMany('two', 'foreign_two', 'two');
});

P.S. I have Laravel 6.X

Upvotes: 0

Views: 319

Answers (1)

OMR
OMR

Reputation: 12188

i recommend using eloquent-dynamic-relation

you can install it:

composer require i-rocky/eloquent-dynamic-relation

in your model use the trait:

    use Rocky\Eloquent\HasDynamicRelation;

class MyModel extends Model {
  use HasDynamicRelation;
}

then you can simply write:

MyModel::addDynamicRelation('some_relation', function (MyModel $myModel) {
    return $myModel->hasMany(SomeRelatedModel::class);
});

Upvotes: 1

Related Questions