2014-08-31 115 views
-4

我想在表格用戶中獲得用戶名,在帖子表中發帖ID並返回View::make('post.index')。我需要在post.index刀片中查看。需要幫助laravel 4.2

Database 
users table 

id 
username 

post table 
    id 
    message 
    posts_id 

Post.php @models folder 

    public function posts() 
    { 
     return $this->belongsTo('User'); 
    } 

User.php @models folder 


    public function post() 
    { 
     return $this->hasMany('Post'); 
    } 





PostController.php @controller folder 
    public function index() 
     { 

     $posts = Post::with('username')->get(); 
     return View::make('post.index')->with('posts', $posts); 
     } 




post/index.blade.php 

     the result here 
     i need to the result of author id become the username 
+2

道歉,但你所寫的內容非常模糊, 。你能否編輯一下,以便更清楚地解決你想解決的問題? – rayryeng 2014-08-31 05:05:42

+0

嗨rayryeng謝謝我更新帖子需要幫助,讓author_id獲取用戶表中的用戶名 – btn25 2014-08-31 05:21:19

+0

好的,這有點更好。我希望有人能夠幫助你。祝你好運! – rayryeng 2014-08-31 05:23:50

回答

0

最佳做法: 模型類的名字應該是UserPost。數據庫表名應該是usersposts

Post.php文件,

public function user() 
{ 
    return $this->belongsTo('User'); 
} 
User.php文件


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

在事先你PostController.php

public function index() 
{ 
    $user_of_the_post = Post::find(postId)->user; //replace the postId //this will return the user object of the specified post 
    $user_name_of_the_author = $user_of_the_post->username; 
    **pass the necessary data to the view and print and return the view** 
} 
+0

等待我更新我得到的錯誤 – btn25 2014-08-31 06:36:17

+0

是有'公共功能的用戶(){ 回報 $這個 - >屬於關聯(「用戶」 ); }在Post模型中的方法? – 2014-08-31 06:46:30

+0

是的我在post.php模型文件夾中 – btn25 2014-08-31 06:48:49