
Laravel:連接三個表進行資料檢索
在這個場景中,您正在建立一個類似Twitter 的應用程序,您需要在其中顯示當前用戶的帖子用戶正在關注。由於您有三個表,即 Users、Followers 和 Shares,因此了解如何有效地連接它們對於檢索所需資料至關重要。
目標是檢索 Shares 表中的 user_id 與Followers 表中的 follower_id,並且 Followers 表中的 user_id 與 Users 表中的 id 相符。
使用資料庫查詢產生器
您嘗試使用以下查詢:
1 2 3 4 5 6 | <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>
|
登入後複製
但是,此查詢的問題在於分享和追蹤者的連線條件。正確的連接應該是:
1 | <code class = "php" >->leftjoin( 'followers' , 'shares.user_id' , '=' , 'followers.user_id' )</code>
|
登入後複製
使用模型增強功能
建議使用Laravel 模型來實現更結構化和更有效率的資料庫操作方法,而不是使用資料庫查詢建構器.
以下是如何定義模型:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <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>
|
登入後複製
使用模型執行查詢
定義模型後,您可以執行以下查詢:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <code class = "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( 'shares.*' );
foreach ( $shares as $share ) {
echo $share ->user->username;
}</code>
|
登入後複製
在此範例中,查詢會擷取所有股票,其中Shares 表中的user_id 與Followers 表中的follower_id 匹配,並且Followers 表中的user_id 與$my 變數中儲存的當前使用者ID 匹配。
以上是如何在 Laravel 中高效連接三個表格來檢索關注用戶的貼文?的詳細內容。更多資訊請關注PHP中文網其他相關文章!