PHP [SOLVED]: laravel – Updating relation with many 'childs'

PHP [SOLVED]: laravel – Updating relation with many 'childs'

Home Forums Scripting PHP Tutorials PHP [SOLVED]: laravel – Updating relation with many 'childs'

Tagged: , ,

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #245526

    Cloudy Point
    Keymaster

    QuestionQuestion

    I have this database:
    parents

    | id |  name  |  
    +----+--------+  
    |  1 |  Paul  |  
    |  2 |  Annet |
    

    childs

    | id |    name   |  
    +----+-----------+  
    |  1 |  Micheal  |  
    |  2 |   Susan   |
    

    and pivot table parents_childs

    | parent_id | child_id | custom_field_1 | custom_field_2 |  
    +-----------+----------+----------------+----------------+  
    |     1     |     1    |    value_1     |      (null)    |  
    |     2     |     1    |  value_another |     value_3    |
    

    and standard relation belongsToMany

    public function parents(): IlluminateDatabaseEloquentRelationsBelongsToMany
    {
        return $this->belongsToMany('AppParent', 'parents_childs', 'child_id', 'parent_id')
                    ->withPivot(
                        'custom_field_1',
                        'custom_field_2'
                    );
    }
    

    Now I need to update pivot fields of specified child but only for one parent, eg.

    SET red_value FOR custom_field_2 WHERE child_id = 1 AND parent_id = 2
    

    How can I do this without QueryBuilder?

    #245527

    Cloudy Point
    Keymaster

    Accepted AnswerAnswer

    From the docs:

    If you need to update an existing row in your pivot table, you may use updateExistingPivot method. This method accepts the pivot record foreign key and an array of attributes to update:

    $child = Child::find($childId);
    $child->parents()->updateExistingPivot($parentId, ['custom_field_2' => 'red_value']);
    

    https://laravel.com/docs/5.5/eloquent-relationships#updating-many-to-many-relationships

    Source: https://stackoverflow.com/questions/48020087/laravel-updating-relation-with-many-childs
    Author: Alexey Mezenin
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.