简体   繁体   中英

How do I get the `pivot table` model to trigger the save/saved model events when attach or detach are called in Laravel?

In Laravel 4 how do I get the pivot table model to trigger the save/saved model events when attach or detach are called?

It seems that the pivot table 'TeamUser' below is not actually needed for the attach/detach methods to work, so at a guess I believe that the model representing the pivot table is never invoked. And so the events are never triggered.

To ask another way: When I call User::with('Team')->find(1)->teams()->attach(1); how to get TeamUser to trigger it's own events. Note that the above attach works perfectly fine, all the records are updated in the database.

User

class User extends Eloquent 
{
    // Relationship
    public function teams() 
    {
        return $this->belongsToMany('Team');
    }    
}

Team

class Team extends Eloquent 
{
    // Relationship
    public function users() 
    {
        return $this->belongsToMany('User');
    }    
}

Team User - The model for the TeamUser table/pivot table

class TeamUser extends Eloquent 
{
    public function save(array $options = array())
    {
        // do cool stuff when relationship is saved via
        // attach/detach
    }
}

You can add a $touches to the Team model.

class Team extends Eloquent 
{
    protected $touches = array('TeamUser');

    // Relationship
    public function users() 
    {
        return $this->belongsToMany('User');
    }    
}

This will update the TeamUser updated_at field. I think this will also hit the save() method in the TeamUser model.

If that doesn't work, you can fire your own event in the Team save() method and listen to this event somewhere.

Event::fire('team.updated', array($team));

With the new version of Laraval 5.8, Pivot tables trigger the boot events. Check the release notes: https://laravel.com/docs/5.8/releases#pivot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM