[英]retrieving data attribute from one to many relationship in laravel
i have a one to many relationship as defiened below 我有一个下面定义的一对多关系
public function property() {
return $this->hasOne(Property::class);
}
and 和
public function propertycalendars(){
return $this->hasMany(PropertyCalendar::class,'property_id');
}
and here in my controller i get the relation like this : 在我的控制器中,我得到这样的关系:
$property = Property::with('propertycalendars')->get();
return view('users.properties.show',compact('property'));
but in view if i try to get title of property it says 但鉴于我试图获得财产所有权,它说
Property [title] does not exist on this collection instance
i wana get the title and the relation attribute that i defined and here is the dd of my $propery which shows the data is there but i just dont know how to access it by the way its the show method of laravel 我想得到我定义的标题和关联属性,这是我的$ 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 [▶]
}
]
}
This line: 这行:
$property = Property::with('propertycalendars')->get();
doesn't fetch one property, it fetches all your properties into a collection. 不获取一个属性,而是将所有属性获取到一个集合中。 Each of those properties has a title.
每个属性都有一个标题。
You'd typically @foreach
through these in the view: 您通常会在视图中通过
@foreach
进行以下操作:
@foreach($property as $prop)
{{ $prop->title }}
@endforeach
(I'd rename $property
to $properties
for clarity, incidentally.) (为了清楚起见,我将
$property
重命名$property
$properties
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.