我有一个下面定义的一对多关系
public function property() {
return $this->hasOne(Property::class);
}
和
public function propertycalendars(){
return $this->hasMany(PropertyCalendar::class,'property_id');
}
在我的控制器中,我得到这样的关系:
$property = Property::with('propertycalendars')->get();
return view('users.properties.show',compact('property'));
但鉴于我试图获得财产所有权,它说
Property [title] does not exist on this collection instance
我想得到我定义的标题和关系属性,这是我的$ propery的dd,它显示数据在那里,但我只是不知道如何通过laravel的show方法来访问它
Collection {#1297 ▼
#items: array:1 [▼
0 => Property {#1245 ▼
#connection: "mysql"
#table: "properties"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:12 [▶]
#original: array:12 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼
"propertycalendars" => Collection {#1296 ▼
#items: array:1 [▼
0 => PropertyCalendar {#1291 ▼
#connection: "mysql"
#table: "property_calendars"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:6 [▶]
#original: array:6 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
]
}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#guarded: array:1 [▶]
}
]
}
这行:
$property = Property::with('propertycalendars')->get();
不获取一个属性,而是将所有属性获取到一个集合中。这些属性中的每一个都有一个标题。
您通常会@foreach
在视图中浏览这些内容:
@foreach($property as $prop)
{{ $prop->title }}
@endforeach
(顺便说一句$property
,$properties
为了清楚起见,我改名为。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句