Laravel有很多关系没有访问这种关系

时间:2014-04-23 19:25:06

标签: php laravel foreach laravel-4

控制器功能(这应该返回2个结果,包括它们的位置和消息数):

public function getIndex()
    {   
        $alerts = User::with('alerts.location')
                  ->where('id', '=', Auth::user()->id)->get();
        $this->layout->content = View::make('agents.index', 
                  array('alerts' => $alerts));
    }

用户模型:

public function alerts()
    {
        return $this->hasMany('Alert');
    }

警报模型:

public function location()
    {
        return $this->belongsTo('Location');
    }

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function messages()
    {
        return $this->hasMany('Message');
    }

查看:

 @foreach($alerts as $alert)
  <tr>
    <td>{{ $alert->location->address_1}}</td>
    <td>{{ $alert->location->address_2}}</td>
    <td>{{ $alert->location->address_3}}</td>
    <td>{{ $alert->location->postcode}}</td>
    <td>{{ $alert->messages->count()}}</td>
  </tr>
  @endforeach

尝试访问locationmessages的任何回音均失败 -

  

ErrorException试图获取非对象的属性

我将查询从 - &gt; first()方法更改为 - &gt; get()方法,这是问题开始的地方。每个警报肯定有多条消息和一个与之关联的位置。

2 个答案:

答案 0 :(得分:0)

看起来$ alerts是一个User数组,您将其用作Alert数组。 试试这个:

$alerts = User::with('alerts.location')
          ->where('id', '=', Auth::user()->id)->first()->alerts;

get()的问题在于它返回一个数组,即使有0或1个结果,看起来你只想要一个结果。

答案 1 :(得分:0)

$alerts = User::with('alerts.location')->where('id', '=', Auth::user()->id)->get();

上面的行返回一个用户模型的Eloquent Collection,其中包含预先加载的嵌套关系,但不是您想要的警报,并且您不会在此处加载消息,因此您将在foreach循环中遇到n + 1问题。 此外,您已经在Auth :: user()中加载了用户,因此无需再次查询用户表。

而是使用它:

$alerts = Auth::user()->alerts // this loads all alerts as a Collection
           ->load('location')  // here we eager load related Location for every Alert
           ->load('messages'); // and here we eager load related messages for all Alerts


// now $allerts is a Collection of Alert models and related Local models
// so this will work (Still add some check for ->location as it might be null
// if there is no related location for an alert):
  @foreach($alerts as $alert)
  <tr>
    <td>{{ $alert->location->address_1 }}</td>
    <td>{{ $alert->location->address_2 }}</td>
    <td>{{ $alert->location->address_3 }}</td>
    <td>{{ $alert->location->postcode }}</td>
    <td>{{ $alert->messages->count() }}</td>
  </tr>
  @endforeach
相关问题