【发布时间】:2020-08-03 16:44:14
【问题描述】:
我开始做一个小项目,我有两个模型建筑和公寓,每个建筑可以有很多公寓。
所以我创建了模型之间的关系,但是当我尝试访问父级时出现错误( Building )
这是我的模型:
//Building.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Apartment;
class Building extends Model
{
protected $guarded = [];
public function apartment(){
return $this->hasMany(Apartment::class);
}
}
//Apartment.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Building;
class Apartment extends Model
{
protected $guarded = [];
public function building(){
return $this->belongsTo(Building::class);
}
}
我的控制器:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Apartment;
use App\Building;
public function index()
{
$apartment = Apartment::with('building')->get();
return $apartment->building;
}
错误信息:Property [building] does not exist on this collection instance.
我想得到这样的结果:
Building 1
Apartment A
Apartment b
Building 2
Apartment A
b 公寓
【问题讨论】:
标签: laravel