Laravel 5 Laravel 5动态变形法

Laravel 5 Laravel 5动态变形法,laravel-5,relationship,Laravel 5,Relationship,我正在构建一个很大程度上依赖于变形多关系的包。与此关系一样,需要定义如下关系: public function foos() { return $this->morphToMany('App\Models\Foo', 'barable'); } 这显然很好,这里没有问题 但问题是,这些关系中有许多需要定义。我只想循环使用它们并自动构建它们,以使配置包更容易 我尝试了以下方法: public function __get($name) { if($name == 'foos

我正在构建一个很大程度上依赖于变形多关系的包。与此关系一样,需要定义如下关系:

public function foos()
{
    return $this->morphToMany('App\Models\Foo', 'barable');
}
这显然很好,这里没有问题

但问题是,这些关系中有许多需要定义。我只想循环使用它们并自动构建它们,以使配置包更容易

我尝试了以下方法:

public function __get($name)
{
    if($name == 'foos') {
        return $this->morphToMany('App\Models\Foo', 'barable');
    }
}
这不会启动检索数据的查询。它被调用,但不返回数据

调用函数对我来说似乎也是合乎逻辑的,但这恰恰打破了拉威尔的逻辑。据我所知,它能收集到课堂上所有被调用的内容

现在的另一种选择是包含一个trait,让程序员在可发布的文件中填写这些关系,但这感觉不对


有什么建议吗?

这是一个两步回答。您需要一个用于快速加载的修复程序和一个用于延迟加载的修复程序

急切加载程序接受model.php中指定的_call()函数,并在语句失败时重定向到该函数

public function __call($method, $arguments){
    if(in_array($method, ['bars'])) {
        return $this->morphToMany('App\Bar', 'barable');
    }
    return parent::__call($method, $arguments);
}
惰性加载程序检查该方法是否存在,但显然不存在。将它添加到您的模型中并添加“OR”语句也会使这些工作正常。原始函数也驻留在model.php中。添加:

 || in_array($key, $this->morphs)
将使功能按预期工作,从而产生:

public function getRelationValue($key)
{
    // If the key already exists in the relationships array, it just means the
    // relationship has already been loaded, so we'll just return it out of
    // here because there is no need to query within the relations twice.
    if ($this->relationLoaded($key)) {
        return $this->relations[$key];
    }

    // If the "attribute" exists as a method on the model, we will just assume
    // it is a relationship and will load and return results from the query
    // and hydrate the relationship's value on the "relationships" array.
    if (method_exists($this, $key) || in_array($key, $this->morphs)) {
        return $this->getRelationshipFromMethod($key);
    }
}