【问题标题】:Laravel getting class on view without passing from controllerLaravel 在视图中获取类而不从控制器传递
【发布时间】: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);
    }
}

显示关注用户的所有帖子的主视图与心形按钮一起使用,但在下方我想显示 和其他 30 人喜欢,其中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结尾。????

标签: php laravel


【解决方案1】:

当处理多对多时,你需要使用数据透视函数,所以你会这样做

Post::profilesHearted()->wherePivotIn('profile_id', $users)->first()

没有检查代码,但希望它会给你这个想法。

【讨论】:

  • 谢谢,这就是我所做的和它的工作。请让我知道是否有更简洁的方法来编写此代码。 @php $heartedUser = $post->profilesHearted()->wherePivotIn('profile_id', $users)->first(); @endphp @if( $heartedUser )

    喜欢 {{ App\User::where('id', '=', $heartedUser->pivot->profile_id )->first()->username }} 和{{ $post->profilesHearted->count()-1 }} 其他人。

猜你喜欢
  • 2019-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-08
  • 2017-01-29
  • 2017-03-31
  • 2018-06-11
相关资源
最近更新 更多