很多人都在Laravel的同桌上

问题描述 投票:0回答:1

我有点失望......我正在尝试用belongsTo加入我的桌子,但我遇到了问题。

我有这张桌子:派对

Id - day - 小丑 - 化妆1 - 化妆2 ...

小丑,化妆1,化妆2都是外键,参考人表。

人民表:

Id - 名字 - 名字......

在我的系统中,小丑,化妆1和化妆2的值是人表的ID。这很好。

问题是当我想要显示小丑,化妆品1和化妆品2的名称时。

我有错误

试图获得非对象的属性

在我的模型中,我定义了这样的关系:

public function people()
{
    return $this->belongsTo(People::class, 'clown', 'id');
}
public function makeup1()
{
    return $this->belongsTo(People::class, 'makeup1', 'id');
}
public function makeup2()
{
    return $this->belongsTo(People::class, 'makeup2', 'id');
}

在我看来,我这样展示小丑:

{{ $defaut->people->name }}

它有效,但另一个没有。

{{ $defaut-> makeup1->name }}
{{ $defaut-> makeup2->name }}

- >不工作和表演

试图获得非对象的属性

我不明白....

PS:我在控制器中的要求是

$defaults = Default::with('people')->with('makeup1')->with('makeup2')->get();

这个工作,我看到var_dump()中的关系。

<pre>Collection {#654 ▼
#items: array:1 [▼
0 => Default {#619 ▼
  #table: "defaults"
  #fillable: array:8 [▶]
  #connection: "mysql"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:11 [▶]
  #original: array:11 [▶]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: array:3 [▼
    "people" => People {#655 ▶}
    "makeup1" => People {#687 ▶}
    "makeup2" => People {#719 ▼
      #fillable: array:7 [▶]
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:10 [▶]
      #original: array:10 [▶]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
    }
  ]
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [▶]
}
]
}
</pre>
Thank you for your advices
php mysql laravel eloquent belongs-to
1个回答
0
投票

我找到了解决方案!为了表明我必须写的关系:

{{ $defaut->makeup1()->first()->name }}

谢谢

© www.soinside.com 2019 - 2024. All rights reserved.