未定义的偏移量0,具有雄辩的集合

时间:2015-08-31 07:10:52

标签: php laravel collections orm

当我尝试像这样进行查询时:

$result = Entity::with (
    [ 'councils' => function ($query) use ($userId) {
        $query->active()->with([
        'members' => function ($query) use ($userId) {
            $query->where ('user', $userId);
        }
        ])->first();
    }])->find ($entityId);

但雄辩的回归关系到一个数组。我需要使用这样的东西:

$result->councils[0]->members[0]->pivot->role;

如何在没有数组偏移的情况下获得集合并使用上述结果:

$result->councils->members->pivot->role;

来自dd()变量的$result

 #attributes: array:15 [▶]
  #original: array:15 [▶]
  #relations: array:1 [▼
    "councils" => Collection {#362 ▼
      #items: array:1 [▼
        0 => Council {#360 ▼
          #guarded: array:1 [▶]
          #connection: null
          #table: null
          #primaryKey: "id"
          #perPage: 15
          +incrementing: true
          +timestamps: true
          #attributes: array:14 [▶]
          #original: array:14 [▶]
          #relations: array:1 [▼
            "members" => Collection {#364 ▼
              #items: array:1 [▼
                0 => User {#359 ▶}
              ]
            }
          ]
          #hidden: []
          #visible: []
          #appends: []
          #fillable: []
          #dates: []
          #dateFormat: null
          #casts: []
          #touches: []
          #observables: []
          #with: []
          #morphClass: null
          +exists: true
          +wasRecentlyCreated: false
        }
      ]
    }
  ]

1 个答案:

答案 0 :(得分:1)

要获取集合的第一个元素,请使用->first()

$result->councils->first()->members->first()->pivot->role;

通过密钥使用->find($key)

来获取元素
$result->councils->find(0)->members->find(0)->pivot->role;

首先检查元素是否存在方法->contains($key)

是一个好习惯
if($result->councils->contains(0)) ...

此处有更多信息http://laravel.com/api/5.1/Illuminate/Database/Eloquent/Collection.html