【问题标题】:How to fetch data with one to one relationship using laravel+VueJS如何使用 laravel+VueJS 以一对一的关系获取数据
【发布时间】:2019-07-13 14:57:11
【问题描述】:

如何使用外键显示用户名? 我有 2 张桌子: 用户和部门,一个部门只有一个老板,一个用户只能是一个部门的老板。所以我认为这是一种“一对一的关系”。 部门表将“user_id”作为来自表用户的外键。 在我的Vue中:

<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>

我想显示用户表中具有 user_id 的用户名。 谢谢。


不工作 部门主管:

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

我说的对吗?

【问题讨论】:

    标签: html laravel laravel-5 vue.js vuejs2


    【解决方案1】:

    你需要先定义关系..

    部门模式

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

    现在使用预先加载的部门获取数据。

    控制器功能

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

    现在您可以在department 对象中访问特定的Cheif 对象。

    在 Vue 中

    <td>{{ department.cheif.name }}</td>
    

    【讨论】:

      【解决方案2】:
      1. 执行获取请求以获取用户
      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. 在您的模板中
      <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>
      

      【讨论】:

      • 我得到了部门和主管的数据,但没有显示。不知道为什么!
      • 当我在导航器的控制台中看到数据时,我得到了部门和具有 user_id 但未显示在表格上的用户的数据
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-22
      • 2019-07-17
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      • 2017-07-16
      相关资源
      最近更新 更多