简体   繁体   中英

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');
});

PS I have Laravel 6.X

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM