怎么在Laravel的whereHas闭包中获取计数?

huangapple go评论63阅读模式
英文:

how to get count in whereHas closure in laravel?

问题

我想要那些在他们的票中没有 user_idauth()->user()->id 相同的用户列表:

$users = User::whereHas('tickets', function($query) {
    $query->where('user_id', '!=', auth()->user()->id);
})->get();

用户模型(关系):

public function tickets(){
    return $this->hasMany(Ticket::class, 'to_id');
}

票务表:

user_id // 发件人用户
to_id // 收件人用户

我想要类似于这样的内容:

$users = User::whereHas('tickets', function($query) {
    return $query->where('user_id', '!=', auth()->user()->id)->count() == 0;
})->get();

我的意思是获取那些没有票务联系与 auth()->user() 的用户列表。如何实现这个目标?

英文:

I want the list of users that in their tickets there is no user_id with auth()->user()->id :

$users = User::whereHas('tickets' , function($query) {
        $query->where('user_id' , '!=' , auth()->user()->id);
    })->get();

users model (relation ship) :

public function tickets(){
    return $this->hasMany(Ticket::class , 'to_id');
}

ticket table:

user_id // sender user
to_id // receiver user

I want to some thing like this :

    $users = User::whereHas('tickets' , function($query) {
        return $query->where('user_id' , '!=' , auth()->user()->id)-count() == 0;
    })->get();

I mean a list of users that there is no ticket between them and auth()->user() exists.
how to get that?

答案1

得分: 1

尝试

$users = User::whereNotExists(function ($query) {
    $query->select(DB::raw(1))->from('tickets')->whereRaw('tickets.to_id = users.id')->where('tickets.user_id', auth()->user()->id);
})->get();
英文:

try

$users = User::whereNotExists(function ($query) {
        $query->select(DB::raw(1))->from('tickets')->whereRaw('tickets.to_id = users.id')->where('tickets.user_id' , auth()->user()->id);
    })->get();

答案2

得分: 0

以下是您要翻译的内容:

$users = User::where('id', '!=' , auth()->user()->id)->doesntHave('tickets')->count();

USER Model

public function tickets()
{
    return $this->hasMany(TicketModel::class);
}
英文:
$users = User::where('id' , '!=' , auth()->user()->id)->doesntHave('tickets')->count();

USER Model

  public function tickets()
    {
        return $this->hasMany(TicketModel::class);
    }

huangapple
  • 本文由 发表于 2023年3月15日 19:35:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75744150.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定