[英]How wherePivot() actually works internally in laravel 5?
在Laravel 5中wherePivot()实际上如何在内部工作?
例如,我通过观看教程进行练习,而老师则使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.