Laravel hasOneThrough 关系返回 null

Hap*_*der 1 php orm laravel eloquent has-one-through

我在MySQL数据库中有以下表结构:

Products
    id - integer
    name - string
    user_id -string

Users
    user_id - string
    password - string
    person_id - integer

Persons
    person_id - integer
    name - string
    email - integer
Run Code Online (Sandbox Code Playgroud)

我正在使用产品模型上的关系来获取有关通过谁链接的hasOneThrough详细信息。定义关系的代码如下:PersonUsers

public function product_user()
{
    return $this->hasOneThrough(
        'App\Person',
        'App\User',
        'person_id',
        'person_id',
        'user_id',
        'user_id'
     );
}
Run Code Online (Sandbox Code Playgroud)

但当我null尝试访问该属性时,它一直在product_user给我。null我无法更改数据库结构。在这种情况下如何定义正确的关系?

Kur*_*ars 5

我总是发现定制关系的文档有点缺乏。我将在这里扩展 HasOneThrough:

假设 A 通过 B 拥有一个 C。

这种关系意味着以下将是我们的模式:

model_a
|  a_id    |    name    |
Run Code Online (Sandbox Code Playgroud)
model_b
|  b_id    | model_a_id |    name   |
Run Code Online (Sandbox Code Playgroud)
model_c
|  c_id    | model_b_id |    name   |
Run Code Online (Sandbox Code Playgroud)

要明确定义键,写出我们的关系:

class ModelA extends Model
{
    ...
    
    public function cModel()
    {
        return $this->hasOneThrough(
            ModelC::class,
            ModelB::class,
            'model_a_id', // Key on B that relates to A
            'model_b_id', // Key on C that relates to B
            'a_id',       // Key on A that relates to B
            'b_id',       // Key on B that relates to C
        );
    }
Run Code Online (Sandbox Code Playgroud)

所以对于你的情况来说,它不太有效。您希望“产品通过用户有一个人”,但实际上您有“产品属于属于个人的用户”,这意味着您需要这个自定义包(staudenmeir/belongs-to-through)来添加该关系。你可以像这样使用它:

用户.php

public function person()
{
    return $this->belongsTo(Person::class, 'person_id', 'person_id');
}
Run Code Online (Sandbox Code Playgroud)

产品.php

use \Znck\Eloquent\Relations\BelongsToThrough;

public function user()
{
    return $this->belongsTo(User::class, 'user_id', 'user_id');
}

public function person()
{
    return $this->belongsToThrough(
        Person::class,
        User::class,
        null, // PK on products, null === 'id'
        '',   // The foreign key prefix for the first "through" parent model, in case you need aliasing.
        [
            Person::class => 'person_id',  // PK on persons
            User::class => 'user_id',      // PK on users
        ],
    );
}
Run Code Online (Sandbox Code Playgroud)