douye4254 2015-09-11 13:23
浏览 50
已采纳

Laravel 5.1 - 相对模型的模型观察者

Let's suppose I have the following related tables:

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

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

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

As you see can we have three tables, in which pages and visitors have a many-to-many relationship.

I have successfully implemented an observer class on the pages model class, and now, what ever I do to the pages table gets reflected somewhere else. Using the following code:

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);
    }
}

You get the idea, right?

As it turns out, when the tables that have a one-to-many relationship with the page table get updated, the above observer, observes it. But not for many-to-many relationships(like the above).

Well, now how do I go about this??? How to do the same thing when page_visitor gets updated?

Thanks

  • 写回答

1条回答 默认 最新

  • dourong9253 2015-09-11 15:26
    关注

    I ended up creating a method to use instead of calling attach on every related class.

    // 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();
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了