我有这个关系模型:
我的主要目标是在系统上建立反应,以便可以与N个身份相关(例如:文章,图片,新闻等)
反应模式:
public function up()
{
Schema::create('reactions', function (Blueprint $table){
$table->increments('id');
$table->string('title', 50)->unique()->index();
$table->string('show_text', 20);
$table->smallInteger('ordering')->nullable()->default(null);
});
}
Reactionables模式:
Schema::create('reactionables', function (Blueprint $table) {
$table->increments('id');
$table->integer('reactor_id')->unsigned();
$table->integer('reaction_id')->unsigned();
$table->foreign("reactor_id")->references("id")->on("users");
$table->foreign("reaction_id")->references("id")->on("reactions");
$table->morphs('reactionable');
$table->timestamp('created_at')->nullable();
});
具有“反应”特征(适用于诸如Post,Images等可反应对象):
/**
* Get related reactions
*
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany
*/
public function reactions()
{
return $this->morphToMany(Reaction::class, 'reactionable')
->withPivot(['reactionable_id', 'reactionable_type']);
}
isReactor特性(适用于用户):
/**
* React to given instance
*
* @param Reactionable $reactionable
* @param ReactionType $applied_reaction
*
* @return bool
*/
public function react(Reactionable $reactionable, ReactionType $applied_reaction)
{
$reactionable->reactions()
->detach(
$reactionable->reactions()->where('reactor_id', $this->getKey())->get(['reactions.id'])->toArray()
);
return $this->storeReaction($reactionable, $applied_reaction);
}
/**
* Store reaction
*
* @param Reactionable $reactionable
* @param ReactionType $applied_reaction
*
* @return bool
*/
private function storeReaction(Reactionable $reactionable, ReactionType $applied_reaction)
{
try {
$reactionable->reactions()->attach(
$applied_reaction->getKey(), [
'reactor_id' => $this->getKey(),
'created_at' => Carbon::now()
]
);
return true;
} catch (\Throwable $exception) {
return false;
}
}
这里的主要问题是,有时候(随机地,我不知道它是如何发生的),对某些随机用户的反应会删除所有其他反应。
我什至不知道这是否是解决此问题的最佳方法-我不想在反应之间应用严格的关系〜帖子应用逆向关系,所以这就是为什么我要这样做。