接收所有 parents 作为 Child

Receiving all parents as a Child

鉴于那些简单的 tables:

Parent

id child_id
1 1
2 1
3 2

Child

id value
1 value_x
2 value_y
3 value_z

我希望能够获得所有 parents 作为关系。此场景中不涉及枢轴 table。是这样的: [Child#1] -- 调用关系parents() --> 接收Parent#1和Parent#2

我认为解决此问题的最接近方法是使用 belongsToMany 关系 - 但我无法弄清楚确切的参数调用以使其工作。

[Edit] 为了更好地理解此示例可能会有所帮助:假设 Parent 是文档扫描。这是由 child 扫描仪制作的。因此一次扫描只能由一台扫描仪完成。但是一台扫描仪当然可以扫描多份文件。

非常感谢任何帮助

数据库结构似乎不正确

childtable

中应该有paren_id

创建一个 parent Eloquent 模型 class

<?php

 namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Parent extends Model
{
    public children()
    {
        return $this->hasMany(Child::class);
    }
}

创建 child class

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Child extends Model
{
  public function parents()
   {
       return $this->belongsTo(Parent::class);
   }
}

你可以这样得到parent

$data = Child::with('parents')->get();

当您有一个带有 *_id 字段的 table 时,关系将为 belongsTo,这反过来意味着另一个关系将为 hasMany(或 hasOne).

NB 这仅在您想要关联两个 table 时,即不通过枢轴 table 而不是多态关系时。

这就是关系的样子:

class Parent extends Model
{
    public child()
    {
        return $this->belongsTo(Child::class);
    }
}
class Child extends Model
{
    public parents()
    {
        return $this->hasMany(Parent::class);
    }
}