Laravel获取父级属性

时间:2020-08-03 16:44:14

标签: laravel

我开始从事一个小项目,我有两个模型Building&Apartment,每个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公寓

1 个答案:

答案 0 :(得分:2)

问题在于,get方法获取公寓集合只能获取一个公寓,然后从中获取建筑物。

public function index()
{
    $apartment = Apartment::with('building')->first();
    return $apartment->building;
}

get方法返回包含结果的Illuminate\Support\Collection,其中每个结果都是PHP stdClass对象的实例。您可以通过将该列作为对象的属性进行访问来访问各列的值:

$apartaments = Apartment::with('building')->get();

foreach ($apartments as $apartament) {
    echo $apartament->building;
}