【问题标题】:Get data from polymorphic relations with namespaces从与命名空间的多态关系中获取数据
【发布时间】:2016-01-16 07:41:18
【问题描述】:

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

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

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

在我的其他所有课程中,我都在关注

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

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

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

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

$comments->rel

我找到了article class not found。我正在使用命名空间App\Models\Article 我已经搜索了它,我找到了here 的答案。当我尝试接受的答案时,没有任何反应,错误保持不变。当我尝试同一问题的第二个答案时,我发现

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

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

【问题讨论】:

  • 请发布您的数据库布局

标签: laravel laravel-4 namespaces polymorphic-associations


【解决方案1】:

我有一篇关于此的博文:

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

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

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

其次,在 Comment 类上,在 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 方法添加到特征中,以便任何变形的模型都可以重用该特征和方法。

【讨论】:

  • 实际上我没有得到的一点是,按照你的方法我得到string(18) "app\models\article" 那是类字符串而不是对象。所以假设$comment = Comment::find(1)rel_type article and rel_id 1。那么现在如何从属于该评论的文章表中获取文章的所有属性等文章数据。
  • @user1272333 像以前一样使用$comment->rel。您之前遇到的问题是 rel_type 只是“article”,它试图创建一个不存在的“article”类的新对象。现在,rel_type 是“app\models\article”,它将成功创建一个具有该完整类名的对象。
  • 当我尝试 $comment->rel 它给了我错误 Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
  • 因为 $comment->rel() 返回 null。为什么它返回 null?
  • 嗨,它已修复,因为我在执行 morphTo 时犯了一个错误,因为我没有使用 return 语句。谢谢你的解决方案。
猜你喜欢
  • 1970-01-01
  • 2014-03-15
  • 1970-01-01
  • 2015-04-25
  • 1970-01-01
  • 2010-12-20
  • 1970-01-01
  • 2017-10-28
  • 2015-03-08
相关资源
最近更新 更多