[improvement] Updating `BelongsToMany` relationship doesn't flush the cache
duncanmcclean opened this issue · 3 comments
Brief description
We're running into an issue with this package - when our client goes to add/delete something on a BelongsToMany
relation on the Product model, the list reloads but there's no change. I also see the same list in our site's frontend but the database is updated correctly.
Implementation
We're using this package on our Product
model, relevant code below:
// app/Models/Product.php
use Chelout\RelationshipEvents\Concerns\HasBelongsToEvents;
use Chelout\RelationshipEvents\Concerns\HasBelongsToManyEvents;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Rennokki\QueryCache\Traits\QueryCacheable;
class Product extends Model
{
use HasFactory;
use HasBelongsToEvents;
use HasBelongsToManyEvents;
use QueryCacheable;
protected $guarded = [];
/**
* Invalidate the cache automatically
* upon update in the database.
*
* @var bool
*/
protected static $flushCacheOnUpdate = true;
/**
* Specify the amount of time to cache queries.
* Do not specify or set it to null to disable caching.
*
* @var int|\DateTime
*/
public $cacheFor = 86400;
// ...
}
On this product model, we have a belongsToMany
relationship called bedTypes
:
public function bedTypes()
{
return $this->belongsToMany(BedType::class);
}
I'm aware the BelongsToMany
events aren't handled by this package - would you prefer if I post an issue on the laravel-relationship-events package instead?
In the meantime, I've deployed a workaround:
I've added a pivot model to each of the BelongsToMany
relationships in my ProductModel
. Then on there, I'm just clearing the entire site cache.
public static function booted()
{
static::creating(function ($model) {
Cache::flush();
});
static::updating(function ($model) {
Cache::flush();
});
static::deleting(function ($model) {
Cache::flush();
});
}
Ideally, we would only clear the cache for the current relationship on the current product but I wasn't sure what the cache keys would be for that.
This issue has been automatically closed because it has not had any recent activity.
Use the Cache Tags feature to set and invalidate specific queries based on assigned Redis/Memcached tags.