0

我在 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

我正在使用hasOneThroughProducts 模型上的关系来获取有关Person链接的详细信息Users。定义关系的代码如下:

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

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

4

1 回答 1

1

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

假设 A 通过 B 有一个 C。

这种关系意味着以下将是我们的架构:

model_a
|  a_id    |    name    |
model_b
|  b_id    | model_a_id |    name   |
model_c
|  c_id    | model_b_id |    name   |

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

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_c_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
        );
    }

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

用户.php

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

产品.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
        ],
    );
}
于 2020-07-08T06:56:02.970 回答