我是Laravel的新手,我正在尝试做一个跟随-取消跟随的系统。我试着自己解决这个问题已经有一个星期了,但是我没有找到任何解决方案。我想我做错了控制器中的SQL语句。这是HomeController.php中的代码
public function index()
{
$users = Users::where('id', '!=', auth()->id())->take(3)->get();
$tweets = DB::select("select avatar, name, username, content, hashtag, tweets.updated_at from users join tweets on users.id = tweets.id order by tweets.updated_at DESC");
$topics = DB::select("select distinct topic from tweets");
$follow = DB::select("select users.id, following.id name, avatar, username, following.followed_id from following join users on following.id = users.id");
return view('home', ['users' => $users], array('user' => Auth::user()))->with(['tweets' => $tweets])->with(['topics' => $topics])->with(['follow' => $follow]);
}
这是home.blade.php中的代码
@foreach($follow as $user)
<div class="backgroundColor">
<div class="container">
<br>
<div class="row">
<div class="col-3">
<img class="avatar" src="images/uploads/avatars/{{ $user->avatar }}" alt="pic" width="32px">
</div>
<div class="col-5">
<a href="{{ route('visit') }}">
<h6 class="effect">{{ $user->name }}</h6>
</a>
<h6>{{ $user->username }}</h6>
</div>
<div class="col-4">
@if($user->id == $user->followed_id)
<a id="followBtn" class="btn btn-info" href="">Following</a>
@else
<a id="followBtn" class="btn btn-info" href="">Follow</a>
@endif
</div>
<p style="color: white;">{{ $user->followed_id }}</p>
</div>
</div>
</div>
<div style="border-bottom: 1px solid gray;"></div>
@endforeach
我还展示了SQL模式
Schema::create('following', function (Blueprint $table) {
$table->bigIncrements('following_id');
$table->integer('id')->unsigned();
$table->integer('followed_id');
$table->timestamps();
});
我没有任何错误,但它根本不起作用。我只是想向其他用户展示一下,看看你是否在关注他。在home.blade.php中,我正在尝试将id与followed_id进行比较,如果这是真的,则意味着我正在遵循它。也许我的方法是完全错误的,我不知道。
发布于 2021-05-25 18:37:54
您的Users
模型:
public function following() {
return $this->hasMany(App\Models\Following::class);
}
public function index()
{
$users = Users::where('id', '!=', auth()->id())->with('following')->take(3)->get();
$tweets = DB::select("select avatar, name, username, content, hashtag, tweets.updated_at from users join tweets on users.id = tweets.id order by tweets.updated_at DESC");
$topics = DB::select("select distinct topic from tweets");
return view('home', ['users' => $users], array('user' => Auth::user()))->with(['tweets' => $tweets])->with(['topics' => $topics])->with(['follow' => $follow]);
}
在你的home.blade.php中
/* ... */
<div class="col-4">
@if($user->following->contains(function($follow) { return $follow->following_id === $user->id; }))
<a id="followBtn" class="btn btn-info" href="">Following</a>
@else
<a id="followBtn" class="btn btn-info" href="">Follow</a>
@endif
</div>
/* ... */
https://stackoverflow.com/questions/67686143
复制相似问题