Laravel Eloquent Relationships - Two different delivery addresses associated with one order model

I have two different delivery addresses for each order:

  • Billing Address
  • Delivery address

Both of them have the same fields, so I created only one model for them Address.

Models:

  • The address
  • Order

Each order contains two fields:

  • invoice_address
  • delivery_address

I want each of these fields to point either to the same address (if the user wants the goods to be sent to the address of the invoice), or to two different addresses (if the delivery address is different from the address of the invoices).

How do I create relationships for this purpose?

Here is what I tried:

Order.php

public function orderAddress() {
    return $this->hasOne('App\Address');
}

public function deliveryAddress() {
    return $this->hasOne('App\Address');
}   

Address.php

public function order() {
    return $this->belongsTo('App\Order');
}  

But I can't figure out how to assign two different addresses to the same order.

hasMany(), , , Address.

+4
1

1. Order:

public function orderAddress()
{
    return $this->hasOne('App\Address', 'invoice_address');
}

public function deliveryAddress()
{
    return $this->hasOne('App\Address', 'delivery_address');
}

Address:

public function orderForInvoiceAddress()
{
    return $this->belongsTo('App\Order', 'invoice_address');
}

public function orderForDeliveryddress()
{
    return $this->belongsTo('App\Order', 'delivery_address');
}

2. , - order_id type:

public function orderAddress()
{
    return $this->hasOne('App\Address')->where('type', 1);
}

public function deliveryAddress()
{
    return $this->hasOne('App\Address')->where('type', 2);
}

Address:

public function order()
{
    return $this->belongsTo('App\Order');
}
+3

Source: https://habr.com/ru/post/1692921/


All Articles