2016-09-20 69 views
0

說,我此Laravel 5.3設置如何創建一個連接兩個用戶ID的數據透視表?

用戶表

id | name | password 

用戶模型

class User extends Authenticatable 
{ 
    public function profile() 
    { 
     return $this->hasOne('App\Profile'); 
    } 
} 

資料表

id | user_id 

資料模型

class Profile extends Model 
{ 

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

現在我希望人們能夠遵循彼此的個人資料。我需要製作一個數據透視表,用於建立兩個user_id之間的關係,或將用戶與個人資料或其他內容鏈接(但他們已經鏈接到他們自己的個人資料?),但我不知道如何。我有點失落。也許我看着這個錯誤的方式。

在此先感謝。

回答

3

爲什麼沒有user_follows表具有以下結構:

ID | user_id | follows_id

然後你可以有以下來獲取用戶遵循用戶與用戶,用戶以下,分別爲:

public function follows() 
{ 
    return $this->belongsToMany('App\User', 'user_follows', 'user_id', 'follows_id'); 
} 


public function followers() 
{ 
    return $this->belongsToMany('App\User', 'user_follows', 'follows_id', 'user_id'); 
} 

退房多少一對多的關係,在這裏工作: https://laravel.com/docs/5.3/eloquent-relationships#many-to-many

相關問題