从具有命名空间的多态关系中获取数据

Get data from polymorphic relations with namespaces

我有一条评论 table,其中包含对文章、食谱和产品的评论。所以它是一个 polymorphic 关系。我的评论 table 中有两列 rel_id and rel_type 用于此关系。

现在在我的 Comment.php 我有以下关系

public function rel()
{
    $this->morphTo();
}

在我的其他所有 class 中,我有以下内容

public function comments()
{
    return $this->morphMany('App\Models\Comment', 'rel');
}

当我尝试获取评论的所有者及其所有相关数据时,我发现 class 未找到错误。例如

$comments = Comment::find(1);
echo $comments->rel_type //article

现在,如果我想获取文章的数据,当我尝试时

$comments->rel

我找到了 article class not found。我正在使用命名空间 App\Models\Article 我已经搜索过了,我找到了给出的答案 。当我尝试接受答案时,没有任何反应,错误仍然存​​在。当我尝试对同一个问题的第二个答案时,我发现

 Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation 

我的最终目标是获取评论所有者数据,如 $comments->articles->id 等。请指导我该怎么做?

我有一个关于这个的博客post:

http://andrew.cool/blog/61/Morph-relationships-with-namespaces

您需要做几件事。首先,对于所有有评论的模型,将 $morphClass 变量添加到 class,例如:

class Photo {
    protected $morphClass = 'photo';
}
class Album {
    protected $morphClass = 'album';
}

其次,在评论 class 上,在评论 class 上定义一个名为 $rel_types 的数组。这基本上与您刚才所做的相反,它是从短名称到完整 class 名称的映射。

class Comment {
    protected $rel_types = [
        'album' => \App\Album::class,
        'photo' => \App\Photo::class,
    ];
}

最后,为 rel_type 列定义一个访问器。此访问器将首先从数据库中检索列("album"、"photo" 等),然后将其转换为完整的 class 名称(“\App\Album”、“\App\Photo", 等等)

/**
 * @param  string  $type  short name
 * @return string  full class name
 */
public function getRelTypeAttribute($type)
{
    if ($type === null) {
        return null;
    }

    $type = strtolower($type);
    return array_get($this->rel_types, $type, $type);
}

注意:$morphClass 是 Laravel 实际定义的东西,所以必须这样命名。 $rel_types 可以任意命名,我只是根据您拥有的 rel_type 列命名的。

为了让它变得更好,请将 getRelTypeAttribute 方法添加到特征中,以便变形的任何模型都可以重用该特征和方法。