如何在laravel 5.4中查询hasBelongsToMany关系

时间:2017-05-11 09:00:22

标签: php laravel laravel-5 laravel-5.4

我有点陷入我的流程之间并需要你的见解,我有表用户和tblRelations用于维护用户的朋友以及维护他们之间的关系我现在使用hasBelongsToMany当我&#39我在询问它我得到了一大堆朋友。 问题我哪里出错了?

用户模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
protected $primaryKey= 'userId';
protected $fillable = [
    'firstName',
    'lastName',
    'nickName',
    'email',
    'password',
    'profilePic',
    'phoneNumber',
    'userHeight',
    'userWeight',
    'userVertical',
    'userSchool',
    'homeTownId',
    'cityId',
    'activationCode',
];

protected $hidden = [
    'password', 'remember_token',
];
public function friends()
{
    return $this->belongsToMany('App\Models\User','tblRelations','userId','userId');
}
}

内部UserController

 public function loadFriend(Request $request)
{
    $user = new User();
    $loadFriends = $user->friends()->where('friendStatus',2)->get();
    if(!$loadFriends) {
        $this->setMeta("200", "You have No Friends");
        $this->setData("friendList", $loadFriends);
        return response()->json($this->setResponse());
    }
    $this->setMeta("200", "Friendlist send successfully");
    $this->setData("friendList", $loadFriends);
    return response()->json($this->setResponse());

}

回复

"meta": {
"code": "200",
"message": "Friendlist send successfully"
},
"data": {
"friendList": []
}

关系模型

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Relation extends Model
{
protected $table = 'tblRelations';
protected $primaryKey= 'relationId';
protected $fillable = [
    'userId',
    'friendId',
    'friendStatus',
];
}

用户迁移

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('userId');
        $table->string('firstName');
        $table->string('lastName')->nullable();
        $table->string('nickName')->nullable();
        $table->string('email')->unique();
        $table->string('password');
        $table->string('profilePic')->nullable();
        $table->string('phoneNumber')->nullable();
        $table->double('userHeight')->nullable();
        $table->double('userWeight')->nullable();
        $table->double('userVertical')->nullable();
        $table->string('userSchool')->nullable();
        $table->unsignedInteger('homeTownId')->nullable();
        $table->unsignedInteger('cityId')->nullable();
        $table->unsignedInteger('homeCourtId')->nullable();
        $table->boolean('userStatus')->default(1)->comment('0 FOR INACTIVE 1 FOR ACTIVE');
        $table->unsignedInteger('activationCode')->default(1);
        $table->rememberToken();
        $table->timestamps();
    });

    //Foreign Keys
    Schema::table('users', function (Blueprint $table) {
        $table->foreign('cityId')->references('cityId')->on('tblCities')->onDelete('cascade');
        $table->foreign('homeTownId')->references('cityId')->on('tblCities')->onDelete('cascade');
        $table->foreign('homeCourtId')->references('homeCourtId')->on('tblHomeCourts')->onDelete('cascade');
    });
}

tblRelations迁移

public function up()
{
    Schema::create('tblRelations', function (Blueprint $table) {
        $table->increments('relationId');
        $table->unsignedInteger('userId');
        $table->unsignedInteger('friendId')->comment('userId as friendId');
        $table->boolean('friendStatus')->default(2)->comment('1 FOR REQUEST SENT 2 FOR REQUEST ACCEPT 3 FOR UNFRIEND 4 FOR BLOCK');
        $table->timestamps();
    });
    Schema::table('tblRelations', function (Blueprint $table) {
        //Foreign Keys
        $table->foreign('userId')->references('userId')->on('users')->onDelete('cascade');
        $table->foreign('friendId')->references('userId')->on('users')->onDelete('cascade');
    });
}

1 个答案:

答案 0 :(得分:0)

好吧,经过多次努力,我得到了我想要的东西,有很多东西需要解决才能到达这里我发布它

内部用户模型我需要为两个字段定义关系,因为我在tblRelations中有2个外键

public function friends() {
    return $this->belongsToMany(User::class, 'tblRelations', 'userId', 'friendId');
}

public function friendOf() {

    return $this->belongsToMany(User::class, 'tblRelations', 'friendId', 'userId');

}

然后在UserController中,我需要在laravel中使用eager loading来编写这样的内容:)

public function loadFriend(Request $request)
{
    $loadFriends = User::with(['friends'])->where('userId',$request->userId)->first();
    if(!$loadFriends) {
        $this->setMeta("200", "You have No Friends");
        $this->setData("friendList", $loadFriends);
        return response()->json($this->setResponse());
    }
    $this->setMeta("200", "Friendlist send successfully");
    $this->setData("friendList", $loadFriends->friends);
    return response()->json($this->setResponse());
}