通过多态关系接触口才模型

时间:2018-10-25 09:45:23

标签: php laravel eloquent

Laravel 5.7。我有两个模型,FooContent。它们的关系是多态的,因为Content也可以与其他模型相关:

class Foo extends Model
{
    public function contents()
    {
        return $this->morphToMany('App\Content');
    }
}

class Content extends Model
{
    use LastModified;

    public function foos()
    {
        return $this->morphedByMany('App\Foo');
    }
}

无论何时更新touch模型,我都想Foo模型Content。因此,我对LastModified模型使用了Content特征:

trait LastModified
{
    protected static function bootLastModified()
    {
        static::updating(function ($model) {
            static::updateLastModified($model);
        });
    }

    protected static function updateLastModified($model)
    {
        $foos = $model->foos;
        if (count($foos) > 0) {
            foreach ($foos as $foo) {
                $foo->touch();
            }
        }
    }
}

我的问题是$model->foos返回正确的Foo模型,但是返回了错误的id。每个Foo都有数据透视表行的Foo,而不是id自己的模型ID。这意味着触摸了错误的Foo行。

1 个答案:

答案 0 :(得分:1)

Laravel具有touching parent timestamps的内置功能。<​​/ p>

在内容模型上,您可以添加一个属性,以告知在更新给定模型时应该建立的关系touched

以下方法应该起作用:

class Content extends Model
{
    protected $touches = ['foos'];

    public function foos()
    {
        return $this->morphedByMany('App\Foo');
    }
}

编辑:由于您使用的是静态更新事件,因此您应该从$model->touchOwners()手动调用static::updated