0

I have 2 tables named Company and Customer. 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.

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? Could anyone please help? Thanks.

1 Answers1

0

Try this instead

factory(Company::class, 5)->create()->each(function ($company){
        $company->customers()
            ->createMany(factory(Customer::class, 5)->make()->map->getAttributes());
    });
omar esmaeel
  • 572
  • 1
  • 4
  • 13
  • It's not working! CustomerID's were again repeated. – user14485319 Feb 11 '21 at 09:32
  • Oh, you need to add one to many relation between the tables. you just need to follow the [docs](https://laravel.com/docs/8.x/eloquent-relationships#one-to-many) and it will work. if you stuck I'm here to help – omar esmaeel Feb 11 '21 at 12:30
  • you need also to add company_id column in customers table – omar esmaeel Feb 11 '21 at 12:37
  • Yes added, Is there anyways to check and stop the duplication of CustomerID for the particular company_ID ? Can It be included inside the seeder? – user14485319 Feb 11 '21 at 12:47
  • yes, the one that I provided you with :'D, did you add the customers method in the company model and it still not working? – omar esmaeel Feb 12 '21 at 12:47
  • Yes, added the customers() in the company model. But still not working:-( – user14485319 Feb 12 '21 at 14:20
  • I'm sorry but could you provide me with the customers method code? – omar esmaeel Feb 12 '21 at 16:23
  • This is the Customer() code : public function customers() { return $this->hasMany(Customer::class, 'customer_id', 'id'); } – user14485319 Feb 13 '21 at 15:24
  • it should be `customers() { return $this->hasMany(Customer::class, 'company_id', 'id'); }` or just leave it for laravel to figure it out like so `customers() { return $this->hasMany(Customer::class); }` try that and let's see how it goes – omar esmaeel Feb 13 '21 at 15:43