我有点失望......我正在尝试使用belongsTo加入我的桌子,但我遇到了问题。
我有这张桌子:派对
Id - day - clown - makeup1 - makeup2 ...
小丑,化妆1,化妆2都是外键,参考人表。
人民表:
Id - name - firstname ...
在我的系统中,小丑,化妆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
答案 0 :(得分:0)
我找到了解决方案! 为了表明我必须写的关系:
{{ $defaut->makeup1()->first()->name }}
谢谢