2014-03-25 137 views
3

我想學習使用AngularJs與Laravel。我已閱讀並觀看了許多內容,但我找不到使用Laravel關係的任何內容。我擁有屬於我的Post和Author模型之間的多對多關係。使用刀片時,我可以使用{{$post->author->name}}AngularJS belongsTo-has許多關係

現在我正在嘗試獲取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); 
    } 

} 

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

我靠近的解決方案,但仍然感到困惑我如何才能在郵政服務的作者姓名。任何幫助表示讚賞。

感謝

回答

2

在您的用戶控制器,渴望負荷筆者檢索職位時,這將允許它在角通過post.author

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