How to save entries in many to many polymorphic relationship in Laravel?

后端 未结 1 1143
日久生厌
日久生厌 2021-01-30 02:15

I have an Org model and a Tag model. I want to associate tags with organizations. My database tables and Eloquent models are set up like so ...

org
    id - inte         


        
1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-30 02:27

    You can use all of the belongsToMany methods for this, for polymorphic many-to-many extends that relation:

    // I would call that relation on tag in plural 'entities()' to be more accurate
    
    $tag->entities()->save(new or existing model, array of pivot data, touch parent = true) (used on existing model)
    $tag->entities()->saveMany(array of new or existing models, array of arrays with pivot data)
    $tag->entities()->attach(existing model / id, array of pivot data, touch parent = true)
    $tag->entities()->sync(array of ids, detach = true)
    $tag->entities()->updateExistingPivot(pivot id, array of pivot data, touch)
    

    All of those methods work both ways of course.


    Examples:

    $tag = Tag::first();
    $entity = Entity::find(10);
    
    // save() works with both newly created and existing models:
    $tag->entities()->save(new Entity(...));
    $tag->entities()->save($entity);
    
    // saveMany() like above works with new and/or existing models:
    $tag->entities()->saveMany([$entity, new Entity(...)]);
    
    // attach() works with existing model or its id:
    $tag->entities()->attach($entity);
    $tag->entities()->attach($entity->id);
    
    // sync() works with existing models' ids:
    $tag->entities()->sync([1,5,10]); // detaches all previous relations
    $tag->entities()->sync([1,5,10], false); // does not detach previous relations, attaches new ones skipping existing ids
    

    Your case:

    Route::put('org/{org}', function(Org $org){
    
      $org->description = Input::get('description');
      $org->website = Input::get('website');
      $org->save();
    
      $org->tags()->sync(Input::get('tags'));
    
      // or if you don't want to detach previous tags:
      // $org->tags()->sync(Input::get('tags'), false);
    
    
      return Redirect::to('org/'.$org->id)
        ->with('message', 'Seccessfully updated page!');
    });
    

    0 讨论(0)
提交回复
热议问题