gpt4 book ai didi

php - Laravel- Eloquent -动态定义的关系

转载 作者:行者123 更新时间:2023-12-01 10:33:10 26 4
gpt4 key购买 nike

是否可以动态设置模型的关系?例如,我有模型Page,我想在不实际更改其文件的情况下向其添加关系banners()吗?这样的事情是否存在:

Page::createRelationship('banners', function(){
$this->hasMany('banners');
});

还是类似的东西?无论如何使用魔术方法获取它们,也许我可以动态添加关系?

谢谢!

最佳答案

I've added a package for this i-rocky/eloquent-dynamic-relation



如果有人还在寻找解决方案,这里是一个。如果您认为这是个坏主意,请告诉我。
trait HasDynamicRelation
{
/**
* Store the relations
*
* @var array
*/
private static $dynamic_relations = [];

/**
* Add a new relation
*
* @param $name
* @param $closure
*/
public static function addDynamicRelation($name, $closure)
{
static::$dynamic_relations[$name] = $closure;
}

/**
* Determine if a relation exists in dynamic relationships list
*
* @param $name
*
* @return bool
*/
public static function hasDynamicRelation($name)
{
return array_key_exists($name, static::$dynamic_relations);
}

/**
* If the key exists in relations then
* return call to relation or else
* return the call to the parent
*
* @param $name
*
* @return mixed
*/
public function __get($name)
{
if (static::hasDynamicRelation($name)) {
// check the cache first
if ($this->relationLoaded($name)) {
return $this->relations[$name];
}

// load the relationship
return $this->getRelationshipFromMethod($name);
}

return parent::__get($name);
}

/**
* If the method exists in relations then
* return the relation or else
* return the call to the parent
*
* @param $name
* @param $arguments
*
* @return mixed
*/
public function __call($name, $arguments)
{
if (static::hasDynamicRelation($name)) {
return call_user_func(static::$dynamic_relations[$name], $this);
}

return parent::__call($name, $arguments);
}
}

在模型中添加以下特征
class MyModel extends Model {
use HasDynamicRelation;
}

现在您可以使用以下方法添加新的关系
MyModel::addDynamicRelation('some_relation', function(MyModel $model) {
return $model->hasMany(SomeRelatedModel::class);
});

关于php - Laravel- Eloquent -动态定义的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39448066/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com