0

我有这个关系模型:

在此处输入图像描述

我的主要目标是在系统上建立反应,以便与 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();
    });

hasReactions trait(应用于可反应的东西,如 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;
    }
}

这里的主要问题是,有时(随机,我不知道它是如何发生的),一些随机用户的反应会删除所有其他反应。

我什至不知道这是否是解决这个问题的最佳解决方案 - 我不想在反应之间应用严格的关系〜帖子应用反比关系,所以这就是我申请这个的原因。

4

0 回答 0