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

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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀