建立追随者系统

时间:2019-07-16 02:29:12

标签: php mysql laravel

我正在尝试与关注者一起制作一个应用,但在查看所关注的人时遇到一些麻烦

这是用户模型:

public function books(){
      return $this->hasMany('App\Book', 'book_id');
    }

    public function follows() {
        return $this->hasMany(Follow::class);
    }
    public function isFollowing($target_id)
    {
        return (bool)$this->follows()->where('target_id', $target_id)->first(['id']);
    }

这是跟随模型

class Follow extends Model
{
  protected $fillable = ['target_id'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

这是FollowController

public function follow(User $user)
    {
        if (!Auth::user()->isFollowing($user->id)) {
            // Create a new follow instance for the authenticated user
            Auth::user()->follows()->create([
                'target_id' => $user->id,
            ]);

            return back()->with('success', 'You are now friends with '. $user->name);
        } else {
            return back()->with('error', 'You are already following this person');
        }

    }

这是userController

public function showOwnProfile()
    {
      $usuarioLog=Auth::user();

      $user = User::find($usuarioLog->id);
      $follow=Follow::where("target_id","=",$usuarioLog["id"] )->get();
      $following=Follow::where("user_id","=",$usuarioLog["id"] )->get();


      $userBooks = Book::where('user_id', '=', $usuarioLog["id"])->get();
      $usuarioLog=Auth::user();
      $myBooks=Book::where("user_id","=","$usuarioLog->id")->get();



      $vacLibros=compact("userBooks");
      $vacUser = compact('user', 'follow','following','myBooks','usuarioLog');

      return view("/profile", $vacLibros, $vacUser);
    }

最后是视图(我想在此可视化所关注的人)

<h1>lista de seguidos</h1>

   @forelse ($following as $following_user) //??????

   <p> <a style="color:black; font-weight:bolder"  href="/normalProfile/{{$following_user}}"> {{//?????}}</a></p>

   @empty
   <p> No sigues a nadie</p>
   @endforelse

1 个答案:

答案 0 :(得分:1)

您需要将该列放在{{}}中,将您要调用的列放在此处

<p> <a style="color:black; font-weight:bolder" href="/normalProfile/{{$following_user->column}}"> {{//?????}}</a></p>

由于我不知道您的列名是什么,所以我只输入一列,以便您对其进行编辑。

我在关系查询中不懂,但是尝试一下:

$following=Follow::where("user_id","=",$usuarioLog["id"] )
->join('users', 'users.id', '=', 'follow.target_id')
->select('follow.*','users.*')->get();
相关问题