Skeletor
Skeletor

Reputation: 3413

How can I update a polymorphic many-to-many pivot record (using the exact pivot id) in laravel?

I want to access my polymorphic (many-to-many) relation in pivot level. Lets say I have:

- pages
  id - title
- articles
  id - title - body
- quotes
  id - title - body
- pageables
  id - order - pageable_type - pageable_id - page_id

Now as you can see I have pages that can have articles and quotes. So that I can call a page and its contents (articles and quotes) in an order. For example:

  page1
     article1
     quote3
  page2
     article2
     quote1
  page3
     article1
     quote1
     article1

Note that 'page3' has two 'article1'. A page can have multiple same articles or quotes. Actually that's why I need to update the exact pivot using it's exact row id. Yes I could use the sync() method but it would delete all duplicate records. Even if I would use syncWithoutDetaching() I wouldn't be able to update the exact pivot I want. On the other hand I tried the updateExistingPivot() method but it doesn't update (the exact) pivot as well. For example:

\App\Article::find(1)->pages()->updateExistingPivot(3, ['page_id'=>1]);

Here the first parameter is assumed t o be the id of the page and not the id of the pivot row itself (normally the pivot table hasn't a id at all).

Is there any laravelish way to do that? (except using fluent query builder or not accepting duplicate records at the first place :) )

Upvotes: 1

Views: 345

Answers (1)

sleepless
sleepless

Reputation: 1789

You could do it this way:

public function pages()
{
    return $this->belongsToMany('Page')->withPivot('row_id', 'other_field_in_pivot_table_you_need');
}

\App\Article::find(1)
    ->pages()
    ->newPivotStatement()
    ->where('row_id', $your_row_id)
    ->update(['order' => 5]);

The newPivotStatemant() will be an object of Query\Builder so you won't have any Eloquent features in this case. That should be clear since you don't have an Eloquent model for your pivot table anyway.

Upvotes: 1

Related Questions