简体   繁体   English

如何设置 Laravel hasOne 与自身的关系?

[英]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.我正在 Laravel 中开发一个应用程序,用户可以在其中匹配一个用户。 I am trying to figure out how to setup the hasOne relationship between users.我想弄清楚如何设置用户之间的 hasOne 关系。

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.用户在创建时有一个 match_id 代表他们匹配的用户。 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. -----edit------ 在评论中和一些人讨论后,我在努力中取得了一些进展。 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.由于match_id 在users 表上,关系应该是belongsTo,而不是hasOne。 belongsTo is specified on the model that contains the foreign key.在包含外键的模型上指定了belongsTo。

Also, you should specify the foreign key:此外,您应该指定外键:

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

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

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