亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Laravel 在視圖上獲取類而不從控制器傳遞

Laravel 在視圖上獲取類而不從控制器傳遞

PHP
慕哥9229398 2023-08-06 14:49:04
我有一個數據透視表post_profile,其中包含每個帖子的心(喜歡)。帖子.phpnamespace 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);    }}配置文件.phpnamespace 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> 和其他 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 克隆教程并了解了基礎知識。我所需要的只是給我一些開始的想法。
查看完整描述

1 回答

?
慕碼人8056858

TA貢獻1803條經驗 獲得超6個贊

當處理多對多時,你需要使用樞軸函數,所以你會這樣做

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

沒有檢查代碼,但希望它能給你這個想法。


查看完整回答
反對 回復 2023-08-06
  • 1 回答
  • 0 關注
  • 161 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號