gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 21:19:20 25 4
gpt4 key购买 nike

我有一个评论表,其中包含文章、食谱和产品的评论。所以它是一个多态关系。我的评论表中有两列 rel_id 和 rel_type ,它们用于此关系。

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

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

在我的其他所有类(class)中,我都遵循

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

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

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

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

$comments->rel

我发现未找到文章类。我正在使用命名空间 App\Models\Article 我已经搜索了它,找到了给出的答案 here 。当我尝试接受的答案时,没有任何反应,错误仍然相同。当我尝试同一问题的第二个答案时,我发现

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

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

最佳答案

我有一篇关于此的博客文章:

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

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

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

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

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

最后,为 rel_type 列定义一个访问器。该访问器将首先从数据库中检索列(“album”、“photo”等),然后将其转换为完整的类名(“\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 方法添加到特征中,以便任何变形的模型都可以重用该特征和方法。

关于laravel - 从具有命名空间的多态关系中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33189347/

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