如何按其他表中的记录过滤查询? - laravel

时间:2017-07-27 04:01:31

标签: php sql laravel

这是我目前的问题,我试图找出

我有一个laravel查询,例如下面的

$users = User::where('country', $country)

            ->where('age', '>=' , $lfmin)
            ->where('age', '<=' , $lfmax)
            ->get();                


            return $users;

这一切都很顺利。但我现在有另一个名为datingblockedusers的sql表。该表中的每条记录都具有blockee和blocker的用户ID。我还在datingblockeduser模型中创建了一个静态函数,就像这样

public static function checkblock($id1, $id2)
{
    //check user is blocked
    $query = Datingblockeduser::where('uone', $id1)->where('utwo', $id2)->get();
    if($query->count() > 0)
    {
        return true;
    }
    else
    {
        $query = Datingblockeduser::where('utwo', $id1)->where('uone', $id2)->get();
        if($query->count() > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

如何过滤我的主查询,使得该查询中每个用户的ID不在字段uone或utwo(用户1或用户2)下的datingblockeduser表中

编辑:我想实现与朋友列表相关的阻止列表类型。我这样创建了一个新的迁移

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

在用户模型中我做了这个

// blocked
public function blocked()
{
    $blocked = $this->belongsToMany('User', 'blocked_user', 'user_id', 'blocked_id');
    return $blocked;
}
public function block_user($blocked_id)
{
    $this->blocked()->attach($blocked_id);   // add friend
    $blocked = User::find($blocked_id);       // find your friend, and...
    $blocked->blocked()->attach($this->id);  // add yourself, too
}
public function remove_blocked($blocked_id)
{
    $this->blocked()->detach($blocked_id);   // remove friend
    $blocked = User::find($blocked_id);       // find your friend, and...
    $blocked->blocked()->detach($this->id);  // remove yourself, too
}

现在我可以将它作为上述查询的一部分或从现在开始的任何其他查询使用它,以确保我只返回不在阻止列表中的用户吗?

1 个答案:

答案 0 :(得分:0)

为什么不查询所有被阻止的user_id而不是使用whereNotIn()

更改主查询
// get blocked user id by authenticated user. (change where condition yourself)
$blockedId = Datingblockeduser::where('blocker_id', auth()->id())->pluck('id');

$users = User::where('country', $country)
            ->whereNotIn('id', $blockedId)
            ->where('age', '>=' , $lfmin)
            ->where('age', '<=' , $lfmax)
            ->get();