2017-02-13 18 views
0

好的,所以我試圖建立一種關係,用戶可以關注其他用戶或關注類別。我得到了使用Polomorpic Many to Many關係的建議。現在我試圖創建一個追隨者 - followee的關係,但我無法圍繞如何設置模型和控制器。如何使用與Laravel的多態多對多關係創建追隨者關係?

TABLES

用戶

 Schema::create('users', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->string('email'); 
      $table->string('password'); 
      $table->string('first_name'); 
     }); 

分類

 Schema::create('categories', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->string('category'); 
     }); 

Followables

 Schema::create('followables', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->timestamps(); 
      $table->integer('user_id'); 
      $table->integer('followable_id'); 
      $table->string('followable_type'); 
     }); 

模型

用戶

class User extends Model implements Authenticatable 
{ 

    public function followers() 
    { 
     return $this->morphToMany('App\Followable', 'followable'); 
    } 

    public function following() 
    { 
     return $this->morphedByMany('App\Followable', 'followable'); 
    } 

    //Use to get id from Auth facade 
    public function getId() 
    { 
     return $this->id; 
    } 
} 

隨動

class Followable extends Model 
{ 

    protected $fillable = ['user_id']; 

    public function followable() 
    { 
     return $this->morphTo(); 
    } 

} 

類型模型跟隨關係還不存在,所以我會離開,一出了現在。

控制器

FollowableController

class FollowableController extends Controller 
{ 

    public function followUser($followable_id){ 

     $user_id = Auth::user()->getId(); 
     $followee = User::find($followable_id); 
     $followee->followers()->create(['user_id' => $user_id]); 


     return redirect()->route('get.user', ['user_id' => $followable_id]); 
    } 

} 

說實話我有點被我創建的代碼混淆。這是一些複製和粘貼,而不理解我所做的100%。不管怎麼說,這將創造記錄在數據庫中尋找這樣的:

隨動

------------------------------------------------- 
|Id | user_id | followable_id | followable_type | 
------------------------------------------------- 
|22 | 4  | NULL   | NULL   | 
------------------------------------------------- 
|23 | 0  | 22   | App\User  | 
------------------------------------------------- 

的followable_id是錯誤,似乎使用的是在隨動表中創建的,而不是標識用戶表中的user_id。

那麼,如何解決,以便有只有一條記錄被保存數據庫權利followable_id

+0

你有沒有得到這個固定的? –

+0

我想這次你必須明確地將它添加到用戶模型中的'follower()'關係函數,即'return $ this-> morphMany('App \ Followable','followable',null,'followable_id'); ' –

回答

0

我猜你正在使用錯誤的方法。我不喜歡的東西,繼Laravel的doc例子,morphMany()是足夠了,因爲你的User可以有很多的追隨者,其本身user所以你可以有:

User型號:

public function followers() 
{ 
    return $this->morphMany('App\Followable', 'followable'); 
} 

然後你可以設置來自控制器的user_id(但不要忘記將其添加到可填充)。

希望它有幫助:)

+0

當我嘗試這個時,沒有東西會保存到數據庫中。還有什麼我應該改變? –

+0

@AdamDedanga,你確定你有正確的字段作爲這些表的外鍵。你能找到解決辦法嗎? –