首頁  >  文章  >  資料庫  >  如何根據複雜關係從 Laravel 中的多個表中檢索特定內容,例如建立類似 Twitter 的提要,根據當前用戶關注的用戶過濾貼文?

如何根據複雜關係從 Laravel 中的多個表中檢索特定內容,例如建立類似 Twitter 的提要,根據當前用戶關注的用戶過濾貼文?

Patricia Arquette
Patricia Arquette原創
2024-10-25 07:39:29139瀏覽

How can I retrieve specific content from multiple tables in Laravel based on complex relationships, such as building a Twitter-like feed that filters posts based on users a current user follows?

Laravel 連接多個表格來過濾內容

在本文中,我們解決了使用Laravel 建立社群媒體平台時面臨的常見挑戰:根據多個表之間的複雜關係檢索特定內容。我們將使用原始 SQL 查詢和 Laravel Eloquent ORM 提供全面的解決方案。

問題陳述

目標是建立一個類似 Twitter 的提要來顯示貼文僅來自當前用戶關注的用戶。為此,我們需要根據以下條件過濾「Shares」表:

  • Share.user_id 必須等於Followers.follower_id
  • Followers.user_id 必須等於to Users.id

$shares = DB::table('shares')
    ->join('users', 'users.id', '=', 'shares.user_id')
    ->join('followers', 'followers.user_id', '=', 'users.id')
    ->where('followers.follower_id', '=', 3)
    ->get();

SQL 解決方案

public function shares() {
    return $this->hasMany('Share');
}

public function followers() {
    return $this->belongsToMany('User', 'follows', 'user_id', 'follower_id');
}

public function followees() {
    return $this->belongsToMany('User', 'follows', 'follower_id', 'user_id');
}
雖然提供的原始SQL 查詢可能看起來是正確的,但需要對連接順序和條件進行細微調整正常工作。以下更正後的 SQL 查詢有效地連接三個表並應用指定的過濾:

或者,使用 Eloquent ORM 提供了一種更優雅和封裝的方法。這是一個基於模型的解決方案:

public function user() {
    return $this->belongsTo('User');
}

User.php(模型)

$my = User::find('my_id');

$shares = Share::with('user')
    ->join('follows', 'follows.user_id', '=', 'shares.user_id')
    ->where('follows.follower_id', '=', $my->id)
    ->get();

foreach ($shares as $share) {
    echo $share->user->username;
}

Share.php(模型)

Controller.php(控制器)這種方法提供了更靈活和可維護的解決方案,確保資料完整性和高效查詢。

以上是如何根據複雜關係從 Laravel 中的多個表中檢索特定內容,例如建立類似 Twitter 的提要,根據當前用戶關注的用戶過濾貼文?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn