pedroroccon's avatar

Merging two models (with a prefix)

Hello everyone! Hope you're having a fantastic day.

Well, i'm stuck with my code. I have two models: one called Customer.php and another called Order.php

The customers can make orders in my application (like an ecommerce).

The problem is: In my Order.php I have to replicate the informations of Customer, because if someone removes the customer from my database, I need to still see the informations of customer in my order. So in my migrations I have something like this, let's simplify:

Customer migration: id, code, name, document Order migration: id, code, customer_id, customer_name, customer_document

When I create an order, I select a customer from a select box, which returns me only the customer ID, so in my controller I fetch this ID and get the customer.

I want to "merge" the customer fetched into the orders model, but I have the "customer_" prefix.

You know a better way to do that?

Thanks for all! Have a nice day!

0 likes
2 replies
pedroroccon's avatar

@zainudinnoori Yes, I already created. But my relation between Order.php and Customer.php can be null. Like a said, imagine a scenario that I have an order and for some reason someone removes the customer associated to this order. My application will thrown an error. To avoid this problem, I make the relation nullable, and replicate the customer information in my order.

Here is my relationship in models

// Customer.php

public function orders()
{
    return $this->hasMany(Order::class);
}

// Order.php

public function customer()
{
    return $this->belongsTo(Customer::class);
}

If i can't fetch $order->customer, then I know that there is no relationship.

Please or to participate in this conversation.