peke_peke
peke_peke

Reputation: 551

laravel5 eloquent foreign key hasOne()

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?

Upvotes: 0

Views: 361

Answers (2)

Imran
Imran

Reputation: 4750

Assuming that you have an Transaction model containing payment_method_id() method that define the relationship between transaction and payment method tables. Now, you can access all columns/property from any transaction object. It should be something like followings:

$transection->payment_method_id->name;

Upvotes: 0

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

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

Upvotes: 1

Related Questions