问题
I want to call a function when a related model is added in the backend. This can be achieved by using a pivot model but in that case there must be some pivot data, otherwise the pivot model events are not fired.
I dont need any pivot data but just to listen for the relation added event.
回答1:
I think this was solved see this pull request and API Docs. They added 4 events for Many-to-Many relations : afterAttach, afterDetach, beforeAttach and beforeDetach
回答2:
Well what you ask is complicated and not easely doable.
if you look at the relation manager behaviour's function onRelationManageCreate you can see that it doesn't fire any events.
I'd suggest you extend the behaviour, overwrite the onRelationManageCreate() method with your own, and use your own behaviour instead of the relationmanager behaviour.
public MyRelationController extends RelationController
{
public function afterRelationCreate()
{
}
public function onRelationManageCreate()
{
parent::onRelationManageCreate();
$this->afterRelationCreate();
}
}
This of course does nothing for linking records, selecting in dropdowns, relation form, checkboxlists.
If you truly wish to catch it you need to listen the the onCreate methods of the Models that are created.
回答3:
I guess This will work for "belongsTo" relations only
I think relation is added there but its not directly saved in to database as it will be stored in differed table first so we can intercept it.
https://github.com/octobercms/october/blob/master/modules/backend/behaviors/RelationController.php#L1043
https://github.com/octobercms/library/blob/762bb0a048d103db4d659d3749a02ea4877ba48f/src/Database/Traits/DeferredBinding.php#L36
so if you can listen events on "DeferredBinding" Model table you can achieve what you want.
as in DeferredBinding table it has all the related information :
Schema::create('deferred_bindings', function(Blueprint $table)
{
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('master_type')->index();
$table->string('master_field')->index();
$table->string('slave_type')->index();
$table->string('slave_id')->index();
$table->string('session_key');
$table->boolean('is_bind')->default(true);
$table->timestamps();
});
as you can see you can get lots of information there.
use October\Rain\Database\Models\DeferredBinding as DeferredBindingModel;
use this model then :
DeferredBindingModel::saved(function($model) {
// you can check relations etc if your parent model is foo
// then you can check for which model this data is sotred
// $model->master_type it will be you model's full name space
// you can compare it
if($model->master_type == 'foo') {
// your interception code here
}
}
please let us know if it is help full or not :).
来源:https://stackoverflow.com/questions/43519060/how-to-listen-for-relation-add-events