laravel5 eloquent foreign key hasOne()

- 1 answer

Ad

I've got a transaction table containing the data of transactions like: id|user_id|amount|payment_method_id|...

The payment_methods table contains the different payment methods. Table design is: id|name

Content of the table is like:

1|paypal

2|credit card.

Now I would like to display a transaction history. This works fine but laravel always displays the number of the payment method, not the name. My transaction model looks like:

public function payment_method_id()
 {
  return $this->hasOne('App\Payment_Method', 'id', 'tpayment_method_id');
 }

All the time it displays the number, but not the correct name of payment method. Where's my fault?

Ad

Answer

Ad

You should define relationship this way:

public function paymentMethod()
{
    return $this->belongsTo('App\Payment_Method', 'payment_method_id');
}

And now you can display payment method name this way:

echo $transaction->paymentMethod->name;

In your example you used the same name of relationship as column and you used hasOne relationship instead of belongsTo

Ad
source: stackoverflow.com
Ad