【发布时间】:2020-07-15 06:48:50
【问题描述】:
我有一个数据透视表 post_profile,其中包含每个帖子的心(喜欢)。
Post.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
public function profilesHearted()
{
return $this->belongsToMany(Profile::class);
}
}
Profile.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $guarded = [];
public function profileImage()
{
$imagePath = ($this->image) ? $this->image : 'profile/czyhBQu2YWX6gvBivZrnEs2ORoBwr3d9mzkwxk8k.png';
return $imagePath;
}
public function followers()
{
return $this->belongsToMany(User::class);
}
public function heartedPosts()
{
return $this->belongsToMany(Post::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
显示关注用户的所有帖子的主视图与心形按钮一起使用,但在下方我想显示 x 是第一个关注者用户,如果用户的任何追随者对帖子感兴趣。我尝试了很多方法来获取x,但我有点迷茫。
这是指向视图的PostsController.php 索引函数:
public function index()
{
$users = auth()->user()->following()->pluck('profiles.user_id');
$posts = Post::whereIn('user_id', $users)->with('user')->latest()->paginate(5);
return view('posts.index', compact('posts', 'users' ));
}
我尝试做但在失败后最终删除的方法是在 foreach 循环中获取每个帖子并检查每个 $post->heartedProfiles(contains($users)),但这不起作用。所以我尝试的另一种方法是在我看来,即index.blade.php
@foreach($users as $userid)
User::select('id')->where('profile_id', $userid)->first()
->profile->profilesHearted->find($post->id)
@endforeach
这不起作用,因为 User 类不能直接在视图中使用而无需传递。
我确信在 Laravel 中有一种简单而干净的方法可以做到这一点。这是我第一次使用 Laravel 和 ORM 编程,所以真的很迷茫。参加了 FreeCodeCamp Instagram 克隆教程并了解了基础知识。我所需要的只是给我一些开始的想法。
【问题讨论】:
-
我想帮忙,但是你能用一句话说明你到底想做什么吗?您想显示“被 John Doe 和其他 30 人点赞”吗?
-
是的,我想证明这一点。从 PostsControllermphp Post-heatredprofiles.find(user.followers) 传递这个。我的英语不太好解释,所以我总是以essayssorry结尾。????