简体   繁体   English

Laravel Eloquent 一对一关系返回空集合

[英]Laravel Eloquent one-to-one relationship returning empty collection

I am on a project where I am using custom PKs and FKs, and I'm trying to set up a one to one relationship.我在一个使用自定义 PK 和 FK 的项目中,我正在尝试建立一对一的关系。

For example, in Employee.php:例如,在 Employee.php 中:

public function title()
{
    return $this->hasOne('App\Title', 'TitleID');
}

On Tinker, I can retrieve an employee TitleID like so:在 Tinker 上,我可以像这样检索员工 TitleID:

$employee = Employee::first();
$employee->TitleID;

Which returns:返回:

"6" “6”

I have now made a model: Title.php:我现在做了一个 model: Title.php:

class Title extends Model
{
    protected $table = "dbo.title";

    protected $primaryKey = 'TitleID';

}

I can retrieve the contents of this model correctly when running $title = Title::all();运行$title = Title::all(); in Tinker.在廷克。

I have set up a new relationship in Employee.php:我在 Employee.php 中建立了新的关系:

public function title()
{
    return $this->hasOne('App\Title', 'TitleID');
}

However, in Tinker (which I have restarted) when I run:但是,当我运行时,在 Tinker(我已重新启动)中:

$employee = Employee::first();
$employee->title()->get();

It returns:它返回:

Illuminate\Database\Eloquent\Collection {#3027 all: [], } Illuminate\Database\Eloquent\Collection {#3027 all: [], }

What have I done to set up this relationship incorrectly?我做了什么来错误地建立这种关系?

The issue was that because the primary key of the other table isn't id , it wasn't able to find the collection.问题是因为另一个表的主键不是id ,所以它无法找到集合。

However, according to the documentation, it reads:但是,根据文档,它显示:

Additionally, Eloquent assumes that the foreign key should have a value matching the id (or the custom $primaryKey) column of the parent.此外,Eloquent 假定外键的值应与父级的 id(或自定义 $primaryKey)列匹配。

So I assumed that because I set a custom $primaryKey value, it would intuitively be able to find it - however it seems the issue was to do with the local key's name breaking Eloquent's convention.所以我假设因为我设置了一个自定义的$primaryKey值,所以它可以直观地找到它 - 但是似乎问题与本地键的名称打破了 Eloquent 的约定有关。

I solved the issue by declaring both the foreign and local key respectively:我通过分别声明外键和本地键解决了这个问题:

public function title()
{
    return $this->hasOne('App\Title', 'TitleID', 'TitleID');
}

You just need to access the property title instead of calling title() :您只需要访问属性title而不是调用title()

$employee = Employee::first();
$employee->title;

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

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