【问题标题】:Multiple Traits on one model from chelout/laravel-relationship-events来自 chelout/laravel-relationship-events 的一个模型的多个特征
【发布时间】:2020-12-11 06:50:48
【问题描述】:

我正在构建一个模型并使用 chelout/laravel-relationship-events 来捕获事件。

我有一个看起来像这样的模型:

    class Taxonomyterm extends Model
    {
    use HasMorphToManyEvents, HasMorphedByManyEvents {
        HasMorphedByManyEvents::newMorphToMany insteadof HasMorphToManyEvents;
    }
    ...
    public function images()
    {
        return $this->morphToMany(Image::class, 'imageable')->withTimestamps();
    }

    public function items()
    {
        return $this->morphedByMany(Item::class, 'taxonomytermable')->orderBy('taxonomytermables.id')->withPivot('id')->withTimestamps();
    }
    ...    
    protected static function boot()
    {
        parent::boot();
        static::morphToManyAttached(function ($relation, $parent, $ids, $attributes) {
            if( $relation == 'images') {
                dd('Attached MorphToMany');
            }
        }

        static::morphedByManyAttached(function ($relation, $parent, $ids, $attributes) {
            if( $relation == 'items') {
                dd('Attached MorphedByMany');
            }
        }
    }

我被包的维护者指向 PHP docs,但似乎找不到正确的方法来完成这项工作。

我还假设 newMorphToMany 是两个特征之间发生冲突的方法。

我基本上不知道该怎么做才能让 HasMorphToManyEvents 和 HasMorphedByManyEvents 在同一个模型上工作。 Package this is from

【问题讨论】:

  • 这样试试,如果成功我会给你更多信息..use HasMorphToManyEvents, HasMorphedByManyEvents { HasMorphedByManyEvents::newMorphToMany as public HasMorphToManyEvents; }
  • 这给了我:尚未应用特征方法 newMorphToMany,因为与 App\\Taxonomyterm 上的其他特征方法存在冲突
  • 实际上,我没有看到您的代码有任何错误。您当前的代码执行错误是什么?
  • 任何错误信息?有任何 github 仓库可以在本地试用吗?
  • HasMorphedByMany 和 HasMorphToMany 都使用 newMorphToMany 方法并且相互冲突,因此您不能在一个模型上同时使用这两种方法。

标签: laravel polymorphic-associations laravel-7.x laravel-events


【解决方案1】:

您需要确定这两个特征之间的冲突方法。假设newMorphToMany是冲突方法:

如果您需要它们都可用,则需要将其中一个重命名如下。

class Taxonomyterm extends Model
{
    use HasMorphToManyEvents, HasMorphedByManyEvents {
        HasMorphedByManyEvents::newMorphToMany insteadof HasMorphToManyEvents;
        HasMorphToManyEvents::newMorphToMany as newMorphToMany2;
    }
    // ... more code
}

现在,无论您需要在Taxonomyterm class 中使用HasMorphToManyEvents::newMorphToMany 的任何位置,都可以使用它的新名称newMorphToMany2 来调用它。否则,newMorphToMany 将始终在此类中引用 HasMorphedByManyEvents::newMorphToMany。 只是强调一下,您需要找出并确定这两个特征中的冲突方法。我希望这会引导您找到解决方案...

【讨论】:

  • 如何让事件使用 newMorphToMany2?
猜你喜欢
  • 1970-01-01
  • 2022-12-04
  • 2022-04-26
  • 1970-01-01
  • 1970-01-01
  • 2020-09-03
  • 2018-01-12
  • 2021-04-01
  • 2019-02-25
相关资源
最近更新 更多