Laravel 連接3 個表
要連接Laravel 中的三個表
$shares = DB::table('shares') ->join('users', 'users.id', '=', 'shares.user_id') ->join('followers', 'followers.user_id', '=', 'users.id') ->where('followers.follower_id', '=', 3) ->get();
要連接Laravel 中的三個表
要連接Laravel 中的三個表// Define User Model 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'); } } // Define Share Model class Share extends Model { public function user() { return $this->belongsTo('User'); } } // Model Usage $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; }
以上是如何在 Laravel 中連接三個表格以獲得類似 Twitter 的 Feed?的詳細內容。更多資訊請關注PHP中文網其他相關文章!