Laravel 5.1 - 相关模型上的模型观察者

Laravel 5.1 - Model observer on relative models

假设我有以下相关的 tables:

pages
----------------
id 
content

visitors
----------------
id
name

page_visitor
----------------
page_id
visitor_id

如你所见,我们可以有3个table,其中pagesvisitors是多对多关系

我已经在 pages 模型 class 上成功实施了观察者 class,现在,我对页面 table 所做的一切都会在其他地方得到反映。使用以下代码:

class ElasticsearchPageObserver
{
    private $elasticsearch;

    public function __construct(ESClient $client)
    {
        $this->elasticsearch = $client;
    }

    public function created(Page $page)
    {
        $params = $page->buildElasticsearchParams();
        $response = $this->elasticsearch->index($params);
    }

    public function updated(Page $page)
    {
        $params = $page->buildElasticsearchParams();
        $response = $this->elasticsearch->index($params);
    }
}

你明白了吧?

事实证明,当与页面 table 具有一对多关系的 table 更新时,上面的观察者会观察到它。但不适用于多对多关系(如上)。

那么,现在我该怎么做呢??? page_visitor 更新后如何做同样的事情?

谢谢

我最终创建了一个方法来使用而不是在每个相关的 class 上调用 attach

// in page:
public function attachTo($to, $id)
    {
        switch($to) {
            case 'App\Models\Visitor':
                $this->visitors()->attach($id);
                break;
            case 'App\Models\Banner':
                $this->banners()->attach($id);
                break;
            case 'App\Models\AdBlock':
                $this->adblocks()->attach($id);
                break;
            default:
                return;
        }
        $this->indexInElasticsearch();
    }