我有一个用户表。用户可以上传帖子。帖子很好地保存到数据库中。用户可以互相关注 - 因此在数据透视表中,每个follower_id都有followees_id。
我需要获取当前用户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}','HubController@get_followee_posts')->name('followee_posts');
我收到的错误是当前代码说:
ErrorException in 7340f90cc5faf1a298fcc646b7248b22 line 105:
Trying to get property of non-object
任何帮助都很可爱。谢谢。
答案 0 :(得分: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);