在laravel vue中获得帖子作者

时间:2018-08-11 14:48:44

标签: laravel vue.js

以刀片式方式,当我们在帖子和用户之间建立关系时,我们可以像{{$post->user->name}}这样检索帖子作者,而我正在使用vue,我想像{{post.user.name}}一样做,但是它没有不返回作者信息。

它在控制台中给了我这个错误:

[Vue warn]: Error in render: "TypeError: Cannot read property 'name' of undefined"

TypeError: Cannot read property 'name' of undefined

代码

<script>
    export default {
        data() {
            return {
                posts: []
            }
        },
        mounted: function() {
            this.load()
        },
        methods: {
            load: function() {
                axios.get('/api/posts')
                .then(
                    response => {
                        this.posts=  (response.data.posts);
                    }     
                )
                .catch(function (error) {
                    this.errors.push(error);
                    console.log(error);
                })
            }
        }
    }
</script>

有什么主意吗?

更新

user model

public function posts()
    {
        return $this->hasMany(Post::class);
    }

Post model

public function User()
    {
        return $this->belongsTo(User::class);
    }

Controller

public function index()
    {
        $posts = Post::orderby('id', 'desc')->get();
        return response()->json([
            "posts" => $posts
        ], 200);
    }

1 个答案:

答案 0 :(得分:1)

如我所料,您必须返回这样的帖子数据:

Ps:使用您自己的帖子字段进行更新。

public function index()
    {
        $posts = Post::orderby('id', 'desc')->get();

         return $posts->map(function($post) {
            return [
                 'id' => $post->id,
                'title' => $post->title,
                'description' => $post->description,
                'user' => $post->user->name
            ];
        });
    }

,并且必须编辑您的组件:

<script>
    export default {
        data() {
            return {
                posts: []
            }
        },
        mounted: function() {
            this.load()
        },
        methods: {
            load: function() {
                axios.get('/api/posts')
                .then(
                    response => {
                        this.posts=  (response.data);
                    }     
                )
                .catch(function (error) {
                    this.errors.push(error);
                    console.log(error);
                })
            }
        }
    }
</script>