简体   繁体   English

Laravel eloquent 如何动态创建关系?

[英]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.我需要使用不同的表和外键为我的模型动态创建不同的关系(oneToOne、manyToMany、oneToMany),然后使用所有这些关系检索我的模型。 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 PS 我有 Laravel 6.X

i recommend using eloquent-dynamic-relation我建议使用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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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