2016-03-03 143 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