第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

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

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

PHP
慕哥9229398 2023-08-06 14:49:04
我有一個(gè)數(shù)據(jù)透視表post_profile,其中包含每個(gè)帖子的心(喜歡)。帖子.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);    }}顯示關(guān)注用戶的所有帖子的主視圖與心形按鈕一起工作,但在下面我想顯示<x> 和其他 30 個(gè)人的喜歡,x如果用戶的任何關(guān)注者喜歡該帖子,則該用戶的第一個(gè)關(guān)注者在哪里。我嘗試了很多方法,x但我有點(diǎn)迷失。這是PostsController.php指向視圖的索引函數(shù):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 循環(huán)中的每個(gè)帖子并檢查每個(gè)帖子$post->heartedProfiles(contains($users)),但這不起作用。所以我認(rèn)為我嘗試的另一種方法是,index.blade.php@foreach($users as $userid)    User::select('id')->where('profile_id', $userid)->first()        ->profile->profilesHearted->find($post->id)@endforeach這是行不通的,因?yàn)閁ser類不能在不傳遞的情況下直接在視圖中使用。我確信 Laravel 中有一種簡單且干凈的方法可以做到這一點(diǎn)。這是我第一次使用 Laravel 和 ORM 編程,所以真的感到失落。學(xué)習(xí)了 FreeCodeCamp Instagram 克隆教程并了解了基礎(chǔ)知識(shí)。我所需要的只是給我一些開始的想法。
查看完整描述

1 回答

?
慕碼人8056858

TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超6個(gè)贊

當(dāng)處理多對多時(shí),你需要使用樞軸函數(shù),所以你會(huì)這樣做

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

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


查看完整回答
反對 回復(fù) 2023-08-06
  • 1 回答
  • 0 關(guān)注
  • 160 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號