N
N
Nikolay2017-05-25 20:48:12
Laravel
Nikolay, 2017-05-25 20:48:12

Is it possible in Laravel 5.4 to get (display) title by ID from another column?

Greetings!
Tell me, is it possible in Laravel 5.4 using relations (or in any other way) to get (display) the title by ID from another column?
For example, there are two tables:

[user]
| id | name  | country_id |
| 1  | Vasya | 2          |
| 2  | Petya | 1          |

and
[country]
| id | name   |
| 1  | USA    |
| 2  | Russia |

How can you get (output) a query (something like JOIN), for example,
Vasya, Russia
Petya, USA

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
Nikolay, 2017-05-26
@iNickolay

The answer turned out to be a bit more complicated:
Additional fields must be specified in the App\User model:

public function country() {
  return $this->hasOne('App\Country', 'id', 'country_id');
}

and in App\Country
public function user() {
  return $this->belongsTo('App\User');
}

Well, bring out$user->country()->name;

B
Barmunk, 2017-05-25
@Barmunk

you can https://laravel.com/docs/5.4/eloquent-relationships specifically in your example it is "one to one"

R
riot26, 2017-05-25
@riot26

In the App\User model:

public function country()
{
    return $this->belongsTo('App\Country', 'country_id');
}

There should be an App\Country model and then:
I can't vouch for the answer, there is no way to check it yet.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question