用户建议Laravel

时间:2018-09-19 12:04:46

标签: database laravel controller eloquent

我想向登录的用户显示用户建议。

应该向已登录用户尚未follow并且user还没有blocked并且是blocked的用户显示。

我如何相应地查询呢?

功能:

$id = Auth::id();
$users = User::with('profile')->where('id', '!=', $id )->inRandomOrder()->get();

与用户模型的关系

 public function followers()
    {
        return $this->belongsToMany(User::class, 'followers', 'leader_id', 'follower_id')->withTimestamps();
    }

    public function followings()
    {
        return $this->belongsToMany(User::class, 'followers', 'follower_id', 'leader_id')->withTimestamps();
    }

    public function blockers()
    {
        return $this->belongsToMany(User::class, 'blockers', 'leader_id', 'block_id')->withTimestamps();
    }

    public function blockings()
    {
        return $this->belongsToMany(User::class, 'blockers', 'block_id', 'leader_id')->withTimestamps();
    }

表格阻止程序

Schema::create('blockers', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('block_id')->unsigned();
            $table->integer('leader_id')->unsigned();
            $table->timestamps();

            $table->foreign('block_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('leader_id')->references('id')->on('users')->onDelete('cascade');
        });

表关注者

Schema::create('followers', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('follower_id')->unsigned();
            $table->integer('leader_id')->unsigned();
            $table->timestamps();

            $table->foreign('follower_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('leader_id')->references('id')->on('users')->onDelete('cascade');

2 个答案:

答案 0 :(得分:1)

您可以使用whereDoesntHave()查询方法,该方法将检查是否存在关系。

首先,您需要获取当前已认证的user的{​​{1}}。然后在每张支票中,您都需要传递此id以便在支票中使用。

示例:

id

答案 1 :(得分:0)

正如我发现的那样,您在UserModel追随者中具有关系,追随,阻止,阻止,但是您想选择与此用户没有任何关系的用户,因此请使用WhereDosentHave,例如:

{.x}

我没有测试它,但我认为工作只是检查关系的名称