我正在尝试制作一个有追随者的应用程序,但在视图中我很难看到我所关注的人
这是用户模型:
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);
}
}
这是下面的控制器
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');
}
}
这是用户控制器
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
最佳答案
你需要把这个列放在{{}}
把你所说的列放在这里
<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();