问题访问PHP对象中的关系

时间:2015-07-27 12:55:24

标签: php oop laravel-4

我正在使用Laravel 4并拥有这一行:

$report->car_info->id

我通常会访问' car_info'像这样:

Undefined property: Illuminate\Database\Eloquent\Collection::$car_info

但这次我收到错误:

object(Illuminate\Database\Eloquent\Collection)#823 (1) {
  ["items":protected] array(1) {
    [0] object(DeliveryProfitReport)#798 (20) {
      ["table":protected] "delivery_profit_reports"
      ["guarded":protected] array(0) {
     }
     ["connection":protected] NULL
     ["primaryKey":protected] "id"
     ["perPage":protected] 15
     ["incrementing"] true
     ["timestamps"] true
     ["attributes":protected] array(29) {
       ["id"] "13"
       ["updated_at"] "2015-07-15 10:11:39"
       ["created_at"] "2015-07-15 10:11:39"
     }
     ["original":protected] array(29) {
       ["id"] "13"
       ["updated_at"] "2015-07-15 10:11:39"
       ["created_at"] "2015-07-15 10:11:39"
     }
     ["relations":protected] array(2) {
       ["car_info"] object(Car)#801 (29) {
         ["connection":protected] "main_site"
         ["timestamps"] false
         ["hidden":protected] array(7) {
           [0] "basic_incl_options"
         }
... and so on.

对象看起来像这样(如果我dd()$ report):

class User {

var id: String
var firstName: String?
var lastName: String?
var email: String
var permissions: String?
var birthday: String?
var subscription: String?


init(id: String, firstName: String?, lastName: String?, email: String, permissions: String?, birthday: String?, subscription: String?) {
    self.id = id
    self.firstName = firstName
    self.lastName = lastName
    self.email = email
    self.permissions = permissions
    self.birthday = birthday
    self.subscription = subscription
}

2 个答案:

答案 0 :(得分:0)

这里的问题是get()返回一个数组。

更改为first()

$report = DeliveryProfitReport::where('id', $id)->with('car_info', 'basic_customer')->first();

将删除dd()中的顶级数组。

否则,您必须执行以下操作:

$report[0]->car_info->id

$report = $report[0];然后$report->car_info->id

答案 1 :(得分:0)

这是因为get()返回多维数组。您无法直接访问自己的对象。请尝试使用first()

$report = DeliveryProfitReport::where('id', $id)->with('car_info', 'basic_customer')->get();

$report->first()->car_info;

希望它对你有用