好的,所以我試圖建立一種關係,用戶可以關注其他用戶或關注類別。我得到了使用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?
你有沒有得到這個固定的? –
我想這次你必須明確地將它添加到用戶模型中的'follower()'關係函數,即'return $ this-> morphMany('App \ Followable','followable',null,'followable_id'); ' –