简体   繁体   中英

How to setup laravel hasOne relationships with itself?

I am working on an application in Laravel where users can be matched up with one users. I am trying to figure out how to setup the hasOne relationship between users.

Here is how I have done it so far. Users when they are created have a match_id which represents the user that they are matched to. When they are matched this record gets updated. Here is my table:

Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('event_id');
        $table->foreign('event_id')->references('id')->on('events')->onDelete('cascade');
        $table->unsignedBigInteger('match_id')->nullable();
        $table->foreign('match_id')->references('id')->on('users')->onDelete('cascade');
        $table->string('name');
        $table->string('email');
        $table->timestamps();
    });

In the user model I have set up this relationship:

 public function match() {
    return $this->hasOne(User::class);
}

but as of right now I cannot do something like this and get the expected matched user's information:

$user->match()->get();

After reading the docs here , I see that in such situations you can setup the foreign key and local key. Nevertheless I am having a difficult time figuring this out.

Could someone give me some guidance on how I could do this? I am also open to any suggestions on different implementations.

-----edit------ after discussing with some people in the comments I made some progress in my endeavors. I am able to get some results and have experimented by logging the matches. For whatever reason though I am getting the wrong matches. Look below for more information:

in my controller I log the users name and match after it has been formed:

Log::error($user->match);
Log::error('has matched with:');

Log::error($user);
Log::error('participant:');

in the database here are the users and their matches: 在此处输入图片说明

yet in the logs, the match is not the same: 在此处输入图片说明

Since the match_id is on the users table, the relationship should be belongsTo, not hasOne. belongsTo is specified on the model that contains the foreign key.

Also, you should specify the foreign key:

return $this->belongsTo('App\User', 'match_id');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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