Php Laravel-多对多数据透视表
我有三张桌子,我想和他们联系装运方式、装运公司和付款方式 关系: 装运方式船运公司 数据透视1付款方式 嗯,我想做的是,例如ShipmentMethod_A附加到ShipmentMethod_B,对于这个记录(来自数据透视1),我想通过数据透视2附加来自付款方法表的记录 ShipmentMethod模型:Php Laravel-多对多数据透视表,php,laravel,eloquent,many-to-many,Php,Laravel,Eloquent,Many To Many,我有三张桌子,我想和他们联系装运方式、装运公司和付款方式 关系: 装运方式船运公司 数据透视1付款方式 嗯,我想做的是,例如ShipmentMethod_A附加到ShipmentMethod_B,对于这个记录(来自数据透视1),我想通过数据透视2附加来自付款方法表的记录 ShipmentMethod模型: public function ship_companies() { return $this->belongsToMany(ShipCompany::class, 'shipm
public function ship_companies()
{
return $this->belongsToMany(ShipCompany::class, 'shipment_methods_ship_companies', 'shipment_method_id', 'ship_company_id')->withPivot('price_kc', 'price_ha');
}
船公司模式:
public function shipment_methods()
{
return $this->belongsToMany(ShipCompany::class, 'shipment_methods_ship_companies', 'ship_company_id', 'shipment_method_id');
}
我需要做的是,我想检索特定ShipmentMethod的Shipmany的所有付款,如
ShipmentMethods->ship_companies->pivot->payments_methods
Thanx.我认为最好的方法是为您提供一个扩展了“pivot1”类的
模型。数据透视1应有id列用于数据透视2。所以代码应该是这样的
发货方法模型:
public function ship_companies()
{
return $this->belongsToMany(ShipCompany::class, 'shipment_methods_ship_companies', 'shipment_method_id', 'ship_company_id')->using('App\pivot1')->withPivot('id','price_kc', 'price_ha');
}
use Illuminate\Database\Eloquent\Relations\Pivot;
class pivot1 extends Pivot
{
public function Payment_methods()
{
return $this->belongsToMany(Payment_methods::class, 'pivot2_table_name', 'pivot1_id', 'payment_method_id');
}
}
请注意,我已使用privot将id放入,并使用()方法将chain放入
您的pivot1模型应该是这样的
pivot1型号:
public function ship_companies()
{
return $this->belongsToMany(ShipCompany::class, 'shipment_methods_ship_companies', 'shipment_method_id', 'ship_company_id')->using('App\pivot1')->withPivot('id','price_kc', 'price_ha');
}
use Illuminate\Database\Eloquent\Relations\Pivot;
class pivot1 extends Pivot
{
public function Payment_methods()
{
return $this->belongsToMany(Payment_methods::class, 'pivot2_table_name', 'pivot1_id', 'payment_method_id');
}
}
最后,您可以这样保存到pivot2
由于所有透视关系都返回一组数组,请注意,您需要循环ShipmentMethods->ship\u companys
关系以获得透视关系
希望这有帮助 我很确定你不需要第二个支点(因此,也不需要第二个多对多关系)。您只需要在第一个数据透视表上建立一对多关系,假设每个数据透视记录只有一种付款方式。因此,您可以将该关系和所有其他必需的模型功能添加到该透视模型中,并将其用作自定义模型。阅读文档中的更多内容:付款方式将是smth,如银行账户、信用卡、现金等,并且可以附加到任何船公司,因此船公司1可以有信用卡、现金,但例如船公司2只接受现金。。。另外,使用另一个SM,SC2可以只有卡等。无论如何,您可以将第一个pivot的功能扩展为一个正常的雄辩模型,只需将其注册为自定义模型即可。然后,你可以附加所有你想要的关系,并根据你的意愿计算出你的逻辑。看看我发给你的文件,你有没有试过你写的东西,但没有用?是的,我试过。对我不起作用。$shipmentMethod[0]->shipmentcompanys[0]->pivot->paymentMethods
显示空集合,但$shipmentMethod[0]->shipmentcompanys[0]->pivot
显示新创建的没有关系的pivot模型。我做错了什么?我不知道如何将paymentMethods与pivot in with子句相关联,所以我使用的是$shipmentMethod=shipmentMethod::with(['shipCompanys'])->get()代码>@MichaelMotúz,我也有同样的问题。你找到解决办法了吗?