我与下面定义的一对多关系
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 [▶]
}
]
}
答案 0 :(得分:4)
此行:
$property = Property::with('propertycalendars')->get();
不获取一个属性,而是将您的属性 all 全部获取到集合中。每个属性都有一个标题。
您通常会在视图中@foreach
进行以下操作:
@foreach($property as $prop)
{{ $prop->title }}
@endforeach
(为了清楚起见,我将$property
重命名为$properties
。)