wherePivot() 在 laravel 5 中实际上是如何工作的?

How wherePivot() actually works internally in laravel 5?

wherePivot() 在 laravel 5 中实际上是如何工作的?

例如,我正在通过观看教程进行练习,而老师正在使用 wherePivot() 来构建关系:

public function friendsOfMine(){

    return $this->belongsToMany('Chatty\Models\User','friends','user_id','friend_id');
}

public function friendOf(){

  return $this->belongsToMany('Chatty\Models\User','friends','friend_id','user_id');

}

public function friends(){

  return $this->friendsOfMine()->wherePivot('accepted',true)->get()->merge($this->friendOf()->wherePivot('accepted',true)->get());

} 

谢谢大家..但我想我找到了答案

枢轴 table 是一个数据库 table,它的存在只是为了服务多对多关系。假设您有一个 table 个“客户”和一个 table 个“饮料”。如果您想知道哪个顾客订购了哪种饮料,您必须创建一个数据透视表 table customer_drinks(customer_id, drink_id).

定义枢轴table

class Customer extends \Eloquent {    
    public function drinks()
    {
        return $this->belongsToMany('Drink', 'customer_drinks', 'customer_id', 'drink_id');
    }
}

创建记录

$customer = Customer::find($customer_id);
$customer->drinks()->attach($drink_id); //this executes the insert-query

从数据透视表中删除记录 Table

$customer = Customer::find($customer_id);
$customer->drinks()->detach($drink_id); //this executes the delete-query on the pivot table