You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel多对多关联多布尔状态跟踪与Eloquent模型定义

Eloquent关联实现方案

你的中间表设计符合Laravel多对多关联的规范,由于中间表存储了三类操作状态字段,直接使用belongsToMany定义关联,同时声明中间表的额外字段即可,还可以封装带状态筛选的便捷关联简化业务调用。

User模型代码

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class User extends Model
{
    /**
     * 关联用户所有绑定过操作状态的游戏
     */
    public function games(): BelongsToMany
    {
        return $this->belongsToMany(Game::class, 'users_games')
            ->withPivot(['liked', 'played', 'wishlisted']);
    }

    /**
     * 用户标记为喜欢的游戏
     */
    public function likedGames(): BelongsToMany
    {
        return $this->games()->wherePivot('liked', true);
    }

    /**
     * 用户标记为已玩的游戏
     */
    public function playedGames(): BelongsToMany
    {
        return $this->games()->wherePivot('played', true);
    }

    /**
     * 用户加入愿望单的游戏
     */
    public function wishlistedGames(): BelongsToMany
    {
        return $this->games()->wherePivot('wishlisted', true);
    }
}

Game模型代码

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Game extends Model
{
    /**
     * 关联游戏所有绑定过操作状态的用户
     */
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'users_games')
            ->withPivot(['liked', 'played', 'wishlisted']);
    }

    /**
     * 标记该游戏为喜欢的用户
     */
    public function likedUsers(): BelongsToMany
    {
        return $this->users()->wherePivot('liked', true);
    }

    /**
     * 标记该游戏为已玩的用户
     */
    public function playedUsers(): BelongsToMany
    {
        return $this->users()->wherePivot('played', true);
    }

    /**
     * 将该游戏加入愿望单的用户
     */
    public function wishlistedUsers(): BelongsToMany
    {
        return $this->users()->wherePivot('wishlisted', true);
    }
}

常用操作示例

  • 新增绑定关系,比如给用户标记喜欢ID为1的游戏:
    $user->games()->attach(1, ['liked' => true]);
    
  • 更新已有绑定的状态,比如把ID为2的游戏标记为已玩:
    $user->games()->updateExistingPivot(2, ['played' => true]);
    
  • 直接获取筛选后的列表,比如获取当前用户的愿望单游戏:
    $wishlist = auth()->user()->wishlistedGames;
    
  • 移除绑定关系:
    $user->games()->detach($gameId);
    

注意:你设置的user_id+game_id复合主键完全适配Eloquent多对多关联的默认逻辑,不需要额外调整模型主键配置。如果后续需要记录操作时间,可以在迁移中添加$table->timestamps(),同时在关联定义后链式调用->withTimestamps()即可自动维护创建、更新时间。

内容的提问来源于stack exchange,提问作者sameer manek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 16:06:30