【问题标题】:Difficult to get associate table's record in Vuejs from Laravel collection很难从 Laravel 集合中获取 Vuejs 中的关联表记录
【发布时间】:2018-11-18 06:14:46
【问题描述】:

我正在使用 Vuejs 和 Laravel 构建一个实时提要应用程序,但我发现很难从 Vuejs 中的集合中获取关联数据,是否可以轻松获取这些数据?

这是我的尝试:

<div class="sl-item" v-for="post, index in posts">
      <a href="javascript:void(0)">
        <div class="sl-content">
          {{post}}
          <br>
          ------------------------
          <br>
          {{getUser(post.user_id)}}
        </div>
      </a>
    </div>

这是我打算检索用户记录的方法:

methods: {
    getUser (id)
    {
      return axios.get("/user/getUser/" + id)
      .then(response => {
        console.log(response.data);
        return response.data;
      });
    }
  },

但这就是我得到的:

我可以记录我在控制台中获得的内容,但我无法显示或访问从我的方法返回的内容。

还有其他更简单的方法来实现这一点吗?

【问题讨论】:

    标签: laravel vue.js collections


    【解决方案1】:

    您从集合中获取所有数据。这就是为什么您还会在对象中获得不需要的数据的原因

    在您当前的情况下(无需更改控制器脚本),您可以像这样访问这些数据:

    public function index(Request $request)
    {
        if ($request->ajax()) {
            return Post::with(['user' => function($query){
               $query->select(['id', 'name'])
            }])
                ->select(['id', 'title', 'description'])
                ->get;
        }
    }
    

    如果您在控制器中执行此操作,那么在您的 vue 文件中,

    data:function(){
            return{
                posts: [],
            };
        },
    methods: {
        getPosts ()
        {
          return axios.get("/posts")
          .then(response => {
            this.posts = response.data;
          });
        }
      },
    

    在组件中:

    <div class="sl-item" v-for="post, index in posts">
          <a href="javascript:void(0)">
            <div class="sl-content">
              {{post.title}}
              <br>
              ------------------------
              <br>
              {{ post.user.name }}
            </div>
          </a>
        </div>
    

    【讨论】:

      猜你喜欢
      • 2017-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      相关资源
      最近更新 更多