2014-04-23 41 views
0

控制器功能(即应该返回2分的结果,与他们的位置和消息计数):Laravel的hasMany关系不访问关系

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试图让非对象

的财产,我从一个改变了查询 - > first()方法,到一个 - > get()方法,这是问题开始的地方。每条警报都有多条消息和1个与之相关的位置。

回答

0

看起来像$ alerts是一个User数组,并且您将它用作Alert的数组。 试试这个:

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

以获得问题()是它返回一个数组,即使有0或1的结果,它似乎像你只期待一个结果。

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

上面一行返回雄辩收集一个用户模型与渴望加载嵌套关系,但不是像你提醒想和你在这里做不急于负载信息,所以你会在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