【问题标题】:Displaying related table data in vuejsvuejs中显示相关表数据
【发布时间】:2018-08-26 18:14:32
【问题描述】:

我正在学习 vuejs 并使用 laravel 作为后端 api。我有以下表格

articles、articles_translations 和我在他们的模型中提到了它们之间的关系

我创建了一个vue组件fpr文章

<template>
    <div>
      <div v-for="article in articles" :key="article.articles">
        <h4>{{article.translations}}</h4>
      </div>
    </div>
</template>

<script>
import axios from 'axios'
import { mapGetters } from 'vuex'

    export default {
        layout: 'basic',

        computed: mapGetters({
          locale: 'lang/locale'
        }),
        data: function () {
            return {
                articles: []
            }
        },
        mounted() {
            var app = this;
            console.log(this.locale);
            axios.get('/api/articles')
                .then(response => {
                  // JSON responses are automatically parsed.
                  this.articles = response.data
                })
                .catch(e => {
                  this.errors.push(e)
                })
        }
    }
</script>

this 显示 [ { "id": 1, "article_id": 1, "title": "This is an example title", "subtitle": "this is a subtitle", "content": "this is the content", "locale": "en", "created_at": null, "updated_at": null } ] 符合预期

我想以这种格式显示文章

  1. 文章标题文章
  2. 文章副标题
  3. 文章内容

在刀片中,我通常使用 {{ $article->article_translations->title }} 来获取相关的表格数据。这在 vue 中是如何工作的?如何以我提到的格式显示数据。

【问题讨论】:

    标签: javascript laravel vue.js


    【解决方案1】:

    只需使用 Laravel 查询构建器,内部连接将有助于解决您的问题,这是一个简单的示例,然后您将收到属性或对象的集合。

    解释:users 表得到一个 User 对象,people 表与 user_id 列的用户相关。只需要加入相关的表并得到这个结果

    $users = DB::table('people')
            ->join('users', 'users.id', '=' ,'people.user_id')
            ->select('users.*',
                'first_name',
                'last_name',
                'street_address',
                'city',
                'state',
                'contact_phone'
            )->get();
    
        return response()->json(['data' => $users], 200);
    

    【讨论】:

      【解决方案2】:

      从您发布的内容来看,您可以获得这样的文章翻译属性:

      <div v-for="article in articles" :key="article.articles">
          <div v-for="translation in article.translations">
              <h4>{{ translation.title }}</h4>
              {{ translation.subtitle }}
              {{ translation.content }}
          </div>
      </div>
      

      基本上添加另一个 for 循环,因为您的翻译在一个数组中。然后简单地显示属性。

      【讨论】:

      • 非常感谢。这正是我想要的。
      猜你喜欢
      • 2021-06-21
      • 2020-08-19
      • 2020-02-12
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      • 2018-10-01
      相关资源
      最近更新 更多