代码之家  ›  专栏  ›  技术社区  ›  TheRealPapa

Laravel为用户和朋友建立了雄辩的关系

  •  2
  • TheRealPapa  · 技术社区  · 7 年前

    USERS:
    id, name, pwd, etc...
    
    FRIENDS:
    id, user_id, friend_id
    

    对于FRIENDS表,我有两个外键:

    $t->foreign('user_id')
      ->references('id')
      ->on('users');
    
    $t->foreign('friend_id')
      ->references('id')
      ->on('users');
    

    用户类别:

    /**
     * A user can have many friends
     */
    public function friends()
    {
        return $this->hasMany(User::class, 'friend_id', 'id');
    }
    

    好友类:

    /**
     * A friend can belong to a user
     */
    public function friend()
    {
        return $this->belongsTo(User::class, 'id', 'user_id');
    }
    
    /**
     * A user friends are connected to
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'id', 'friend_id');
    }
    

    我想以

    Auth::user()->friends()->get();
    

    hasManyThrough() ? 当USERS表通过FRIENDS表自引用时,我该如何实现这一点?

    2 回复  |  直到 7 年前
        1
  •  5
  •   Ulrik McArdle    7 年前

    迁移:

    public function up()
    {
        Schema::create('friend_user', function(Blueprint $table) {
            $table->increments('id');
            $table->integer('friend_id')->unsigned()->index();
            $table->integer('user_id')->unsigned()->index();
            $table->foreign('friend_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
    }
    

    用户模型:

    public function friends()
    {
        return $this->belongsToMany(User::class, 'friend_user', 'user_id', 'friend_id');
    }
    

    Auth::user()->friends (or Auth::user()->friends()->get())
    

    添加朋友:

    Auth::user()->friends()->attach([2,3,4]); // Add user_id 2, 3 and 4
    

    删除朋友:

    Auth::user()->friends()->detach([2]); // Remove user_id = 2
    

    Auth::user()->friends()->sync([7]); // Remove old and add user_id = 7
    
        2
  •  0
  •   Dav ___    4 年前

    没有必要 friends 表,因为存在虚2表 users 用户 朋友 桌子