php - Laravel 6.x 处理数据透视表的正确方法
问题描述
我想使用数据透视表将我的Customer
模型与CustomerGroup
Laravel 中的模型连接起来。
我尝试了以下方法:(作为参考,我使用了https://ben.lobaugh.net/blog/204838/how-to-use-custom-pivot-tables-in-laravel-6-x但我可以做到有事吗)
我创建了迁移customer_group_customer
,并在方案中添加了以下内容:
$table->unsignedBigInteger("customer_group_id");
$table->unsignedBigInteger("customer_id");
在模型中Customer
,Customer_groups
我添加了一个功能。函数如下(以Customer
模型为例):
public function groups(){
return $this->belongsToMany("App\CustomerGroup","customer_group_customer","customer_id","customer_group_id");
}
然后我创建了一个客户和一个组,然后手动将它们连接到:
DB::table("customer_group_customer")->insert(["customer_group_id" => $group->id, "customer_id" => $customer->id]);
之后我获取了所有客户并看到没有连接(通过 dd() 我看不到任何关于组或类似的条目):
$customer = \App\Customer::create([]);
$group = \App\CustomerGroup::create(["name" => "hey"]);
DB::table("customer_group_customer")->insert(["customer_group_id" => $group->id, "customer_id" => $customer->id]);
dd(\App\Customer::first());
如何正确设置数据透视表?
有没有更好的方法来创建客户并为其分配一个组,而无需手动使用DB
外观?
解决方案
您没有看到groups
关系dd()
的原因Customer
是因为它尚未加载。
with()
您可以在查询模型时使用加载关系,或者load()
在您拥有模型实例之后,或者只是通过将关系作为属性访问,例如$customer->groups
;
您还可以使用关系到attach
不同的关系,而不是使用DB
外观来手动完成:
$customer = \App\Customer::create([]);
$group = \App\CustomerGroup::create(['name' => 'hey']);
$customer->groups()->attach($group);
dd($customer->groups);
推荐阅读
- google-app-engine - 部署后 Google App Engine 运行命令
- python - pyspark 如何使用两个标题行取消旋转 csv
- javascript - 函数将记录值但返回未定义
- javascript - 如何从 payeezy 支付网关获取交易结果到我的网站 - firstdata Payeezy?
- angularjs - 绑定两个选择角度
- python - 为 Conv2D 模型重塑图像
- c# - 输入下一个字段时输入的日期消失
- button - PySimpleGUI 不返回任何内容
- python - cerberus - 如何验证任意字典键?
- amazon-web-services - 无法担任角色并验证指定的 targetGroupArn。请验证正在传递的 ECS 服务角色是否具有适当的权限