【问题标题】:How to listen for changes on Eloquent MorphToMany pivot table如何监听 Eloquent MorphToMany 数据透视表的变化
【发布时间】:2020-03-23 20:59:28
【问题描述】:

我有 3 个模型(Operator1、Operator2、Operator3),它们都与 PaymentMethods 具有 MorphToMany 关系。关系/数据透视表包含一些特定于单个运算符的附加信息。这是一个示例模型:

class Operator1 extends Model
{
    /**
     * The payment methods of the operator.
     */
    public function paymentMethods()
    {
        return $this->morphToMany('App\PaymentMethod', 'payable')->withPivot([
            'deposit_time',
            'withdrawal_time',
            'deposit_fees',
            'withdrawal_fees',
        ]);
    }
}

我需要监听数据透视表上的变化。在处理BelongsToMany 关系时,我可以使用->using(aPivotModelClass::class) 方法来指定一个自定义的pivot 类模型,然后我可以在其中监听saving、saved、deleted、deleting 等雄辩的事件.

我使用eventually package by altek 不必为每个枢轴执行此操作,但由于我使用Laravel Nova,它不会触发该包提供的事件,因此我需要手动触发它们。我这样做是这样的:

use Illuminate\Database\Eloquent\Relations\Pivot as EloquentPivot;

abstract class Pivot extends EloquentPivot
{
    /**
     * @var string
     */
    public $relationName;

    /**
     * {@inheritDoc}
     */
    public static function boot()
    {
        parent::boot();

        static::saved(function (Pivot $model) {
            $model->pivotParent->firePivotEvent('attached', true, $model->relationName, [$model->attributes]);
        });

        static::deleted(function (Pivot $model) {
            $model->pivotParent->firePivotEvent('detached', true, $model->relationName, [$model->attributes]);
        });
    }
}

到目前为止,这一切都与 BelongsToMany 结合使用,但现在我尝试在 MorphToMany 关系上使用 ->using(SomePivotModel::class) 方法。这不起作用,我收到以下错误:

local.ERROR: Call to undefined method App\Pivots\Payables::setMorphType() {"userId":1,"exception":"[object] (BadMethodCallException(code: 0): Call to undefined method App\\Pivots\\Payables::setMorphType() at /var/www/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50)

如果没有最终或类似的包,我如何才能收听 MorphToMany 数据透视表的更新?

相关:GitHub comment

【问题讨论】:

    标签: php laravel eloquent laravel-nova


    【解决方案1】:

    我怀疑你的 SomePivotModel 模型应该扩展 Illuminate\Database\Eloquent\Relations\Pivot 而应该扩展 Illuminate\Database\Eloquent\Relations\MorphPivot

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-03
      • 2010-11-26
      • 2015-08-26
      • 1970-01-01
      相关资源
      最近更新 更多