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

时间:2015-09-30 21:29:50

标签: php laravel relationship laravel-5.1

whereLivot()在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());

} 

1 个答案:

答案 0 :(得分:2)

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

数据透视表是一种数据库表,仅用于提供多对多关系。假设你有一张桌子“顾客”和一张桌子“喝”。如果您想知道哪个客户订购了哪种饮料,您需要创建一个数据透视表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