0

I have designed 3 tables in mysql Payments, CreditCardPayment, WireTransfer. Payment table has column payment_mode which store the mode of payment used (credit card or paypal). In CreditCardPayment & WireTransfer I am storing the payment id from payment table.

Now how do I fetch all the payments from payment table with the payment mode (details from either credit card or paypal table)?

Suraj Rana
  • 70
  • 13

1 Answers1

1

You must do polymorphic relation the Payment entity and to other entities (CreditCardPayment, WireTransfer).

Add an migration for Payment to adding these columns:

  • paymentable_type (string)
  • paymentable_id (integer)

At the Payment.php (entity) you should add this function:

public function paymentable() {
    return $this->morphTo();
}

At CreditCardPayment.php you should add this function:

public function payments(){
    return $this->morphMany(Payment::class, 'paymentable');
}

At WireTransfer.php you should add this function:

public function payments(){
    return $this->morphMany(Payment::class, 'paymentable');
}

Note: The "Payment" at the "payments" method is your Payment entity class.

Mesuti
  • 878
  • 1
  • 13
  • 29
  • For more information, you look at the Eloquent documentation: https://laravel.com/docs/5.6/eloquent-relationships#polymorphic-relations – Mesuti Jun 10 '18 at 12:15