【问题标题】:Laravel get parent attributesLaravel 获取父属性
【发布时间】: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


【解决方案1】:

问题在于 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;
}

【讨论】:

  • 我怎样才能得到一个包含 Building A Apartment 1 的数组
  • 你必须使用Query Builder进行SQL查询
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-15
  • 1970-01-01
  • 1970-01-01
  • 2021-10-21
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
相关资源
最近更新 更多