繁体   English   中英

如何使用与Laravel的多态多对多关系来创建关注者关系?

[英]How to create follower relationships using Polymorphic Many to Many relationships with Laravel?

好的,所以我正在尝试建立一种关系,使用户可以关注其他用户或关注类别。 我得到了使用Polomorpic多对多关系的建议。 现在,我正在尝试创建一个追随者-追随者关系,但是我不能全神贯注于如何设置模型和控制器。

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();
    }

}

类别模型的追随者关系尚不存在,因此我暂时将其省略。

CONTROLLER

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是错误的 ,似乎使用了在Followable表中创建的ID,而不是User表中的user_id。

那么,如何解决,以确保只有一条记录被 正确的followable_id 保存到数据库中?

我想您使用的是错误的方法。 在Laravel的doc示例之后,我做了类似的事情,并且morphMany()就足够了,因为您的User可以有很多关注者,这些关注者本身就是user因此您可以拥有:

User模型:

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

然后,您可以从控制器设置user_id(但不要忘记将其添加到可填充)。

希望能帮助到你 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM