我正在使用Laravel最新版本进行小型项目,我有两个模型Building和Apartment,并且已经在底部看到了两个模型之间的关系。
我想像这样以分层的方式获得结果。
building_number x
apartment_number x
apartment_number y
apartment_number z
building_number y
apartment_number x
apartment_number y
apartment_number z
这是我的模特:
<?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);
}
}
//
<?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);
}
}
我的控制器功能
public function index()
{
$apartments = Apartment::with('building')->get();
return response()->json($apartments);
}
我现在的结果:
[
{
"id":1,
"apartment_number":"1",
"building_id":1,
"created_at":"2020-08-03T08:46:36.000000Z",
"updated_at":"2020-08-03T08:46:36.000000Z",
"building":{
"id":1,
"building_number":"1"
}
}
]
当您希望在该层次结构中进行操作时,只需进行相反操作即可。您在哪里查询建筑物并包括所有基础公寓。
public function index()
{
$buildings = Building::with('apartments')->get();
return response()->json($buildings);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句