首页 > 解决方案 > Laravel 6.x 处理数据透视表的正确方法

问题描述

我想使用数据透视表将我的Customer模型与CustomerGroupLaravel 中的模型连接起来。

我尝试了以下方法:(作为参考,我使用了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");

在模型中CustomerCustomer_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外观?

标签: phplaravel

解决方案


您没有看到groups关系dd()的原因Customer是因为它尚未加载。

with()您可以在查询模型时使用加载关系,或者load()在您拥有模型实例之后,或者只是通过将关系作为属性访问,例如$customer->groups

Eloquent Eager 加载文档

您还可以使用关系到attach不同的关系,而不是使用DB外观来手动完成:

$customer = \App\Customer::create([]);
$group = \App\CustomerGroup::create(['name' => 'hey']);

$customer->groups()->attach($group);

dd($customer->groups);

附加/分离文档


推荐阅读