Php Where Pivot()在laravel 5中实际如何在内部工作?
Where Pivot()在laravel 5中实际如何在内部工作 例如,我通过观看教程进行练习,老师使用wherePivot()解释关系:Php Where Pivot()在laravel 5中实际如何在内部工作?,php,laravel,relationship,laravel-5.1,Php,Laravel,Relationship,Laravel 5.1,Where Pivot()在laravel 5中实际如何在内部工作 例如,我通过观看教程进行练习,老师使用wherePivot()解释关系: public function friendsOfMine(){ return $this->belongsToMany('Chatty\Models\User','friends','user_id','friend_id'); } public function friendOf(){ return $this->belo
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\u drinks(customer\u id,drink\u 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()->detach($drink_id); //this executes the delete-query on the pivot table
创建记录
$customer = Customer::find($customer_id);
$customer->drinks()->attach($drink_id); //this executes the insert-query
从数据透视表中删除记录
class Customer extends \Eloquent {
public function drinks()
{
return $this->belongsToMany('Drink', 'customer_drinks', 'customer_id', 'drink_id');
}
}
$customer = Customer::find($customer_id);
$customer->drinks()->detach($drink_id); //this executes the delete-query on the pivot table
您检查了吗?wherePivot()
方法允许您在pivot表(即friends
)上约束一列(即accepted
),从而仅选择符合条件的外来记录。