如何在 Laravel 中高效連接三個表格來檢索關注用戶的貼文?

Linda Hamilton
發布: 2024-10-25 07:09:29
原創
954 人瀏覽過

How to Efficiently Join Three Tables in Laravel to Retrieve Posts from Followed Users?

Laravel:連接三個表進行資料檢索

在這個場景中,您正在建立一個類似Twitter 的應用程序,您需要在其中顯示當前用戶的帖子用戶正在關注。由於您有三個表,即 Users、Followers 和 Shares,因此了解如何有效地連接它們對於檢索所需資料至關重要。

目標是檢索 Shares 表中的 user_id 與Followers 表中的 follower_id,並且 Followers 表中的 user_id 與 Users 表中的 id 相符。

使用資料庫查詢產生器

您嘗試使用以下查詢:

<code class="php">$shares = DB::table('shares')
    ->leftjoin('followers', 'shares.user_id', '=', 'followers.follower_id')
    ->leftjoin('users', 'followers.user_id', '=', 'users.id')
    ->where('users.id', 3)
    ->where('shares.user_id', 'followers.follower_id')
    ->get();</code>
登入後複製

但是,此查詢的問題在於分享和追蹤者的連線條件。正確的連接應該是:

<code class="php">->leftjoin('followers', 'shares.user_id', '=', 'followers.user_id')</code>
登入後複製

使用模型增強功能

建議使用Laravel 模型來實現更結構化和更有效率的資料庫操作方法,而不是使用資料庫查詢建構器.

以下是如何定義模型:

<code class="php">class User extends Model {
    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');
    }
}
class Share extends Model {
    public function user() {
        return $this->belongsTo('User');
    }
}</code>
登入後複製

使用模型執行查詢

定義模型後,您可以執行以下查詢:

<code class="php">$my = User::find('my_id');

// Retrieves all shares by users that I follow
// eager loading the "owner" of the share
$shares = Share::with('user')
    ->join('follows', 'follows.user_id', '=', 'shares.user_id')
    ->where('follows.follower_id', '=', $my->id)
    ->get('shares.*'); // Notice the shares.* here

// prints the username of the person who shared something
foreach ($shares as $share) {
    echo $share->user->username;
}</code>
登入後複製

在此範例中,查詢會擷取所有股票,其中Shares 表中的user_id 與Followers 表中的follower_id 匹配,並且Followers 表中的user_id 與$my 變數中儲存的當前使用者ID 匹配。

以上是如何在 Laravel 中高效連接三個表格來檢索關注用戶的貼文?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!