wherepvot()实际上是如何在laravel 5内部工作的


How wherePivot() actually works internally in laravel 5?

wherepevot()如何在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());
} 

谢谢大家。但我想我找到了我的答案

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

定义数据透视表

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

从透视表中删除记录

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