英文:
how to get count in whereHas closure in laravel?
问题
我想要那些在他们的票中没有 user_id
与 auth()->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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论