简体   繁体   English

AngularJS属于To-hasMany关系

[英]AngularJS belongsTo-hasMany relationship

I am trying to learn using AngularJs with Laravel. 我正在尝试使用Laravel使用AngularJs。 I have read and watched many tuts but I could not find any for using Laravel relationships. 我已阅读并观看了许多内容,但我找不到使用Laravel关系的任何内容。 I have belongsTo-many relationships between my Post and Author model.When using blade I can get author names using {{$post->author->name}} 我的Post和Author模型之间有很多关系。当使用刀片我可以使用{{$post->author->name}}获取作者姓名

Now I am trying to get for angularjs. 现在我想获得angularjs。

    class Post extends Eloquent {
    public function author()
        {
            return $this->belongsTo('Author');
        }
    }

    class Author extends Eloquent { 
     public function posts()
        {
            return $this->hasMany('Post');
        }
    }

class UserController extends BaseController {

    public function getIndex(){
        $posts = Post::where('id','<','10')->get();
        return Response::json($posts);
    }

}

With the js files : 使用js文件:

// public/js/controllers/mainCtrl.js
angular.module('mainCtrl', [])
    .controller('mainController', function($scope, $http, Post) { 
        $scope.postsData = {};
        // loading variable to show the spinning loading icon
        $scope.loading = true;

        Post.get()
            .success(function(data) {
                $scope.posts = data;
                $scope.loading = false;
            });
           //dont know how to get author here in foreach method 
           angular.forEach($scope.posts,function(post)...


    });

// public/js/services/commentService.js
angular.module('postService', [])
    .factory('Post', function($http) {

        return {
            // get all the posts
            get : function() {
                return $http.get('/api/posts/');
            }
        }
    });

<div class="comment" ng-hide="loading" ng-repeat="post in posts">
        <h3>Comment #{{ post.id }} </h3> <p>{{post.title}}</p>
        {{post.author_id}} / {{post.author.name}}
</div>

I am close to solution but still confused how do I get the author name in Post service. 我接近解决方案但仍然困惑如何在Post服务中获取作者姓名。 Any helps are appreciated. 任何帮助表示赞赏。

Thanks 谢谢

In your user controller, eager load the author when retrieving the posts, this will allow it to be accessed in angular via post.author 在您的用户控制器中,在检索帖子时急切地加载作者,这将允许通过post.author以角度访问它

public function getIndex(){
    $posts = Post::with('author')->where('id','<','10')->get();
    return Response::json($posts);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM