2016-03-03 48 views
1

我有一个用户表。用户可以上传帖子。该帖子很好地保存到数据库中。用户可以相互关注 - 所以在数据透视表上,每个follower_id都有followees_id。访问用户的属性(使用数据透视表)laravel 5.1

我需要获取当前用户followee的帖子。我有点尴尬从数据透视表中获取它。

这里是我到目前为止的代码:

控制器:

protected function get_followee_posts($followee_posts) ////$followee_posts passed from the route. 
{ 
    $user = $this->user; 
    $user->followee()->attach($followee_posts); 
    $followee_posts = User::find($followee_posts); 


} 

观点:

<div class="following_posts"> 

<p> Posts from people you're following: <p> 


@foreach ($user->follower_id->followee_id->posts as $post) 
<form action="/html/tags/html_form_tag_action.cfm" method="post"> 
<textarea name="comments" id="comments" style="width:96%;height:90px;background-color:white;color:black;border:none;padding:2%;font:22px/30px sans-serif;"> 
{!! $posts->full_post !!} </textarea> 

</form> 
@endforeach 

路线:

Route::get('hub/{followee_posts}','[email protected]_followee_posts')->name('followee_posts'); 

我得到一个错误与当前的代码说:

ErrorException in 7340f90cc5faf1a298fcc646b7248b22 line 105: 
Trying to get property of non-object 

任何帮助将是可爱的。谢谢。

+0

我觉得你使用'附加()'如果不当你的意图是简单地从数据库中检索的记录。 'attach()'用来在一个多对多关系的中间表中插入一条记录。 – Jeemusu

回答

0

你对你的模式不太具体,但这是我的方式。

用户模型

class User extends Model 
{ 
    protected $table = 'users'; 

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


    public function followers() 
    { 
     return $this->hasMany('Follower'); 
    } 
} 

跟随型号

class Follower extends Model 
{ 
    protected $table = 'followers'; 

    public function user() 
    { 
     return $this->belongs_to('User'); 
    } 

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

日志模型

class Post extends Model 
{ 
    protected $table = 'posts'; 

    public function user() 
    { 
     return $this->belongs_to('User'); 
    } 
} 

followers表将是这个样子:

user_id 
follower_id 

然后,您可以用雄辩的方法链得到用户的追随者的帖子:

// Get Users object with followers and followers posts 
// We use with() to eager load relationships 
$user = User::with('followers.posts')->find(2); 

// Return associative array of post objects 
$postsArray = $user->followers->lists('posts'); 

// Combine posts into a single collection 
$posts = (new \Illuminate\Support\Collection($postsArray))->collapse()->toArray(); 

print_r($posts); 
+0

我会让你知道那是怎么回事。我确实有上述所有模型,忘记提及。抱歉。 (我现在睡觉了) – osherdo

+0

@osherdo,稍微编辑了答案,并在全新安装中对其进行了测试。应该做这项工作。 – Jeemusu

+0

@ Jeemusu我在同一张桌子('用户')上都有追随者和追随者,所以都应该在User.php中。我应该将追随者模型合并到User.php模型中吗? – osherdo

相关问题