0

How can I show the name of user using a foreign key? I have 2 tables: users and departements, one departement have only one cheif and a user can be a cheif of only one departement. So I think it's a "one to one relationship". the departement table have the"user_id" as a foreign key from the table users. In the vue I have:

<tr v-for="departement in departements" :key="id" >
                <td>{{departement.id }}</td>
                <td>{{departement.name }}</td>
                <td>{{departement.user_id }}</td>
                <td>{{departement.bio }}</td>

I want to display the name of the user from users table who has the user_id. Thank you.


Dosen't work Department Controller:

public function index()
{
    return Departement::where('name','!=','admin')->latest()->paginate(100);
    $departements = Departement::with('chief')->get();
    return response()->ajax($departements, 200);
}

am i right?

2 Answers 2

1

You need to define relationships first..

Department Modal

public function chief()
{
    return $this->belongsTo('App\User', 'user_id');
}

now fetch the data with eager loaded department.

Controller function

$departments = Department::with('cheif')->get();

Now you can access particular Cheif object in department object.

In Vue

<td>{{ department.cheif.name }}</td>
Sign up to request clarification or add additional context in comments.

Comments

0
  1. Do a get request to get the users
mounted () {
  axios.get('some/api/users')
  .then(res => {
    this.$set(this, 'users', this.users.reduce((accum, user) => accum[user.id] = user, {}))
    // transform the JSON to an object that maps to the user id
  })
}
  1. In your template
<tr v-for="departement in departements" :key="id" >
                <td>{{departement.id }}</td>
                <td>{{departement.name }}</td>
                <td>{{departement.user_id }}</td>
                <td>{{departement.bio }}</td>
                <td>{{users[department.user_id].name}}</td>

2 Comments

I got the data of the departments and the chief but it doesn't display . don't know why!
When i see the data in the console of the navigator I get the data of the department and the user who has the user_id but it has not display on the table

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.