【问题标题】:How to define a relationship that touches grandparents in eloquent如何用雄辩的方式定义触动祖父母的关系
【发布时间】:2014-04-15 17:23:28
【问题描述】:

在 Laravel 中,我想定义一个祖父母类型的 eloquent 关系,以便在添加或更新时让孙子触摸祖父母(例如,如果它给祖父母带来一张非常漂亮的生日贺卡)。假设我有一个像 Collection > post > comment 这样的层次结构。

--Comment--
    protected $touches = array('post', 'collection');

    public function post()
    {
        return $this->belongsTo('Post');
    }
    public function order()
    {
        // not working
        // return $this->post->collection();
        // not working
        // return $this->belongsTo('Post')->belongsTo('Collection');
    }

--Post--
    public function collection()
    {
        return $this->belongsTo('Collection');
    }

我希望在添加评论时运行集合中的更新功能。我该如何设置?

我正在使用 Laravel 4.1

【问题讨论】:

    标签: laravel laravel-4 relationship eloquent


    【解决方案1】:

    我希望集合中的更新功能在评论时运行 已添加。

    我对更新功能有点困惑,但是...

    您可以为此注册一个事件处理程序,例如,将其添加到您的 Comment 模型中:

    class Comment extends Eloquent {
    
        public static function boot()
        {
            parent::boot();
    
            static::created(function($comment)
            {
                // $comment is the current Comment instance
            });
        }
    }
    

    因此,无论何时创建任何Comment,事件处理程序(匿名函数)都会运行,因此您可以在该函数中执行某些操作。阅读更多Laravel Website

    【讨论】:

    • 是的,我的 Collection 类有这个。我计划使用protected $touches = ... 自动更新集合,以便更新运行。虽然它似乎不起作用,所以我可能不得不手动完成
    猜你喜欢
    • 1970-01-01
    • 2018-06-14
    • 2022-06-11
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多