简体   繁体   English

如何防止一对多关系中的重复?

[英]How to prevent the duplication in one-to-many relationship?

I have 2 tables named Company and Customer .我有 2 个名为CompanyCustomertables One-to-Many relationship , where a company can have many customers and a customer belongs to this company.一对多关系一个公司可以有很多客户,一个客户属于这家公司。

Company Table                    Customers Table  
Company Id,                       Customer_ID,    
Company Name,                     Customer_Name,
Company Address                   Phone_no.

In the seeder,在播种机中,

factory(App\Company::class, 5)->create()->each(function ($data) {
            $customers= factory(App\Customer::class, 5)->make();
            $data->customers()->saveMany($customers);

          });

so, each company generates 5 customers each.因此,每家公司各自产生 5 个客户。

The Idea is想法是

company_id         customerId
 1,1,1,1,1         1,2,3,4,5 // the customerId should not be repeated again like 1,2,2,3,4,
 2,2,2,2,2         2,3,6,7,8 // should not be 2,3,3,3,6
 3,3,3,3,3         5,7,8,9,2 and so on 

A company can have many customers but not the customer's with the sameId. How to avoid the duplication for the customerID using php?, and a condition to check if the company has already the customer with the SameId, then remove them from the customer?如何避免使用 php 的客户 ID 重复?以及检查公司是否已经拥有 SameId 的客户的条件,然后将其从客户中删除? Could anyone please help?有人可以帮忙吗? Thanks.谢谢。

Try this instead试试这个

factory(Company::class, 5)->create()->each(function ($company){
        $company->customers()
            ->createMany(factory(Customer::class, 5)->make()->map->getAttributes());
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM