Docs might warn about belongsToMany() and $touches
When using $touches with belongsToMany relation as mentionned in documentation, we can lack of update in the case of a deassociation.
With:
class Article extends Model
{
use Searchable;
protected $touches = ['authors'];
public function authors()
{
return $this->belongsToMany(Authors::class);
}
}
and in the scenario
$article->authors()->attach(1)
$article->authors()->attach(2)
...
$article->authors()->sync([1])
author 2 will not be updated in algolia. Maybe doc could mention this.
Sounds a good idea, to clear understand the idea, can you write bellow a small snippet so a copy/past it into the docs?
Handling deletion with belongsToMany
While using a belongsToMany relationship with a pivot table
class Article extends Model
{
use Searchable;
public function authors()
{
return $this->belongsToMany(Authors::class);
}
}
class Author extends Model
{
protected $touches = ['articles'];
public function articles()
{
return $this->belongsToMany(Article::class);
}
}
be aware that "touches" hook is not triggered when a link is removed between two related items (for example: $article->authors()->detach($author) or $article->authors()->sync([])). So you'll need to handle this additionally.
One way to do this, is to define a custom intermediate table model and hook on delete event to trigger change:
class Author extends Model
{
protected $touches = ['articles'];
public function articles()
{
return $this->belongsToMany(Article::class)->using(ArticleAuthor::class);
}
}
class ArticleAuthor extends Pivot
{
public static function boot()
{
parent::boot();
static::deleting(function ($item) {
Article::find($item->article_id)->touch();
});
}
}
What do you think @nunomaduro ?
IMO the whole "Relationships section" would deserve a dedicated page in the docs.
I will check it next Monday. Thanks for this!
You are right. Can you add bellow this comment the documentation that should end up in the docs? Thank you for your work on this.
I would simply move the https://www.algolia.com/doc/framework-integration/laravel/indexing/configure-searchable-data/?language=php#relationships to a dedicated page as it doesn't fit well in "Customize Searchable Data" in my opinion and it would be easier to navigate/find in the menu.
Being able to PRs the doc would have been a lot easier :)
Sounds good. Going to mark this as docs, and handle it soon as possible.
in the mean time, I made it a blog post: https://medium.com/code16/handling-changes-on-belongstomany-relations-with-laravel-scout-extended-fa72e41143b7
Any update on this?