Mysql 如何使用Scope在雄辩的ORM中选择除(A和B)之外的所有行?

Mysql 如何使用Scope在雄辩的ORM中选择除(A和B)之外的所有行?,mysql,laravel,laravel-4,eloquent,Mysql,Laravel,Laravel 4,Eloquent,我试图找出如何在雄辩的ORM模式中获得除少数A和B之外的所有行 用户模型 模型通知 在这里,我如何获得除友谊和发送范围之外的所有用户通知 Something like:- all rows except !(Friendship AND Sent) 可以将作用域与即时加载结合使用。就像这样: User::with(['notifications' => function($q){ $q->friendship(); }])->get(); 然而,我们现在需要以某种方

我试图找出如何在雄辩的ORM模式中获得除少数A和B之外的所有行

用户模型

模型通知

在这里,我如何获得除友谊和发送范围之外的所有用户通知

Something like:- all rows except !(Friendship AND Sent)

可以将作用域与即时加载结合使用。就像这样:

User::with(['notifications' => function($q){
    $q->friendship();
}])->get();
然而,我们现在需要以某种方式反转范围。我可以想出两种方法来解决这个问题

1.添加负作用域 2.可选参数 或者,您可以在当前作用域中引入一个可选参数。大概是这样的:

public function scopeFriendship($query, $is = true)
{
    return $query->where('object_type', ($is ? '=' : '!='), 'Friendship Request');
}

public function scopeSent($query, $is = true)
{
    return $query->where('verb', ($is ? '=' : '!='), 'sent');
}
这样,您只需通过false:

User::with(['notifications' => function($q){
    $q->friendship(false);
    $q->sent(false);
}])->get();
编辑 您甚至可以通过为其中的布尔AND或or添加第二个参数来获得更多控制:

public function scopeFriendship($query, $is = true, $boolean = 'and')
{
    return $query->where('object_type', ($is ? '=' : '!='), 'Friendship Request', $boolean);
}
如果您希望其中一个范围为真:

$q->friendship(true, 'or');
$q->sent(true, 'or');
第二版 这一次终于在聊天中奏效了

Notification::where('listener_id', $user_id) 
    ->where(function($q){ 
        $q->friendship(false) 
        $q->sent(false, 'or') 
    }) 
    ->get();

你遗漏了一句话,请更正。谢谢你指出我的错误:我以前没有读过Q。。现在来看,我有点怀疑这是可能的。您必须为此操作创建一个新的作用域。类似这样的吗$通知=$user->notifications->whereNotIn'id',通知::where'listener\u id',$user\u id->where'verb','=','sent'->where'object\u display\u name','=','friends Request'->选择'id'->获取->toArray->获取;谢谢你花时间解决我的问题。顺便说一句,我想跟随你的2。可选参数。但是友谊和友谊都是真实的,但结合起来是错误的。像这样的东西:-!友谊是真实的,发送是真实的`是的,如果你用真实来称呼它,你就不能把它们结合起来。然而,也有一种方法可以做到这一点。。给我一分钟,我会更新我的答案,但我怎么能得到全部的错误。我的意思是:-不是友谊,是真的,是真的。一些链接和操作。这将是我发布的第一个代码$q->friendshipfalse$q->sentfalse;。这不起作用吗?我想使用作用域select*from notifications减去select*from notifications,其中object_type='Friendly'u request'和verb='sent';可能吗?
public function scopeFriendship($query, $is = true, $boolean = 'and')
{
    return $query->where('object_type', ($is ? '=' : '!='), 'Friendship Request', $boolean);
}
$q->friendship(true, 'or');
$q->sent(true, 'or');
Notification::where('listener_id', $user_id) 
    ->where(function($q){ 
        $q->friendship(false) 
        $q->sent(false, 'or') 
    }) 
    ->get();