PHP Laravel 5.2 属于

PHP Laravel 5.2 belongs to

我有 3 table 个用户、配置文件和好友。

用户显然包含用户。 然后我得到了个人资料和朋友 table(见下文)。

public function up()
{
    Schema::create('profiles', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->string('picture')->nullable();
        $table->string('status')->nullable();
        $table->string('text')->nullable();
        $table->boolean('show_sex');
        $table->boolean('show_dob');
        $table->timestamps();
    });
}

public function up()
{
    Schema::create('friends', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id_sender')->unsigned();
        $table->integer('user_id_receiver')->unsigned();
        $table->foreign('user_id_sender')->references('id')->on('users');
        $table->foreign('user_id_receiver')->references('id')->on('users');
        $table->integer('status'); // 1 = friends, 2 = under validation
        $table->timestamps();
    });
}

如您所见,我创建了一些与用户相关的外键 table。

The Friends table 包含用户之间的所有友谊(状态字段将确定友谊是否正在验证或已验证)。 我有 Laravel 5.2 附带的默认用户模型,想知道如何轻松获得属于已签名用户的所有友谊? 我可以使用 belongsTo() 之类的东西轻松获取所有 user_id_receiver 字段与签名用户 ID 相同的好友请求吗?我不太了解 hasOne 或 belongsTo 的文档。如果有人能弄清楚它的实际工作原理,那就太好了。

提前致谢。

是的,您应该使用 UserProfile 模型之间的一对一关系以及 UserFriend 模型之间的一对多关系。将此添加到两个模型 - FriendProfile:

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

并将其添加到 User 模型:

public function profile()
{
    return $this->hasOne('app\Profile');
}

public function friend()
{
    return $this->hasMany('app\Friend');
}

然后你可以使用Eloquent获取数据:

$signedUserId = Auth::user()->id;
$currentUserFriendRequests = Friend::where('user_id_receiver', $signedUserId)->get();

希望对您有所帮助。