从Eloquent模型中获取所有关系

时间:2013-12-02 18:02:11

标签: php laravel-4 eloquent

拥有一个Eloquent模型,是否有可能在运行时获得所有关系及其类型?

我试过看一下ReflectionClass,但我找不到任何有用的方法。

例如,如果我们有经典的Post模型,有没有办法提取这样的关系?

- belongsTo: User
- belongsToMany: Tag

4 个答案:

答案 0 :(得分:5)

要做到这一点,你会知道模型中方法的名称 - 它们可以变化很大;)

思想:

  • 如果你在方法中有一个模式,比如relUser / relTag,你可以过滤掉它们

  • 或循环遍历所有公共方法,查看是否弹出Relation对象(不好主意)

  • 您可以定义一个protected $relationMethods(注意:Laravel已经使用$relations),其中包含一个带方法的数组。

在致电Post-> User()后,您将收到来自BelongsTo系列的Relation或其他1个对象,因此您可以列出关系类型。

[编辑:评论后]

如果模型配备了受保护的$with = array(...);,那么您可以在加载记录后查看与$Model->getRelations()的加载关系。当没有加载记录时,这是不可能的,因为尚未触及关系。

getRelations()位于/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php

但目前它没有出现在laravel.com/api的api中 - 这是因为我们有更新的版本

答案 1 :(得分:1)

我最近一直在做同样的事情,我认为如果没有反思,它可以有效地完成。但这有点资源密集,所以我已经应用了一些缓存。需要进行的一项检查是验证返回类型和pre-php7,这只能通过实际执行每种方法来完成。所以我也运用了一些逻辑,在运行检查之前减少了候选人的数量。

/**
 * Identify all relationships for a given model
 *
 * @param   object  $model  Model
 * @param   string  $heritage   A flag that indicates whether parent and/or child relationships should be included
 * @return  array
 */
public function getAllRelations(\Illuminate\Database\Eloquent\Model $model = null, $heritage = 'all')
{
    $model = $model ?: $this;
    $modelName = get_class($model);
    $types = ['children' => 'Has', 'parents' => 'Belongs', 'all' => ''];
    $heritage = in_array($heritage, array_keys($types)) ? $heritage : 'all';
    if (\Illuminate\Support\Facades\Cache::has($modelName."_{$heritage}_relations")) {
        return \Illuminate\Support\Facades\Cache::get($modelName."_{$heritage}_relations"); 
    }

    $reflectionClass = new \ReflectionClass($model);
    $traits = $reflectionClass->getTraits();    // Use this to omit trait methods
    $traitMethodNames = [];
    foreach ($traits as $name => $trait) {
        $traitMethods = $trait->getMethods();
        foreach ($traitMethods as $traitMethod) {
            $traitMethodNames[] = $traitMethod->getName();
        }
    }

    // Checking the return value actually requires executing the method.  So use this to avoid infinite recursion.
    $currentMethod = collect(explode('::', __METHOD__))->last();
    $filter = $types[$heritage];
    $methods = $reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC);  // The method must be public
    $methods = collect($methods)->filter(function ($method) use ($modelName, $traitMethodNames, $currentMethod) {
        $methodName = $method->getName();
        if (!in_array($methodName, $traitMethodNames)   //The method must not originate in a trait
            && strpos($methodName, '__') !== 0  //It must not be a magic method
            && $method->class === $modelName    //It must be in the self scope and not inherited
            && !$method->isStatic() //It must be in the this scope and not static
            && $methodName != $currentMethod    //It must not be an override of this one
        ) {
            $parameters = (new \ReflectionMethod($modelName, $methodName))->getParameters();
            return collect($parameters)->filter(function ($parameter) {
                return !$parameter->isOptional();   // The method must have no required parameters
            })->isEmpty();  // If required parameters exist, this will be false and omit this method
        }
        return false;
    })->mapWithKeys(function ($method) use ($model, $filter) {
        $methodName = $method->getName();
        $relation = $model->$methodName();  //Must return a Relation child. This is why we only want to do this once
        if (is_subclass_of($relation, \Illuminate\Database\Eloquent\Relations\Relation::class)) {
            $type = (new \ReflectionClass($relation))->getShortName();  //If relation is of the desired heritage
            if (!$filter || strpos($type, $filter) === 0) {
                return [$methodName => get_class($relation->getRelated())]; // ['relationName'=>'relatedModelClass']
            }
        }
        return false;   // Remove elements reflecting methods that do not have the desired return type
    })->toArray();

    \Illuminate\Support\Facades\Cache::forever($modelName."_{$heritage}_relations", $methods);
    return $methods;
}

答案 2 :(得分:0)

我对项目有相同的需求。我的解决方案是使用get_class函数来检查关系类型。例如:

 $invoice = App\Models\Invoice::with('customer', 'products', 'invoiceProducts', 'invoiceProduct')->latest()->first();

    foreach ($invoice->getRelations() as $relation => $items) {
        $model = get_class($invoice->{$relation}());
        $type  = explode('\\', $model);
        $type  = $type[count($type) - 1];

        $relations[] = ['name' => $relation, 'type' => $type];
    }
    dd($relations);

示例结果:

array:4 [▼
  0 => array:2 [▼
    "name" => "customer"
    "type" => "BelongsTo"
  ]
  1 => array:2 [▼
    "name" => "products"
    "type" => "BelongsToMany"
  ]
  2 => array:2 [▼
    "name" => "invoiceProducts"
    "type" => "HasMany"
  ]
  3 => array:2 [▼
    "name" => "invoiceProduct"
    "type" => "HasOne"
  ]
]

我需要它来复制包含关系的模型项

答案 3 :(得分:0)

composer require adideas/laravel-get-relationship-eloquent-model

https://packagist.org/packages/adideas/laravel-get-relationship-eloquent-model

Laravel 获取所有 eloquent 模型的关系!

您无需知道模型中方法的名称即可执行此操作。拥有一个或多个 Eloquent 模型,多亏了这个包,你可以在运行时获取它的所有关系和它们的类型