2016-11-30 51 views
1

在我的数据库中,通知和状态表之间有很多关系。所以数据透视表存储了notification_id,statuses_id和values。现在,在我的模型我写了一个函数historysStatus,其提取从数据透视表值和created_at提取数据透视表中的所有记录

public function historystatus() 
{ 
    $o_status = Status::where('name','health')->first(); 
    $o_response = $this->statuses()->where('status_id', $o_status->id) 
    ->select('values','created_at')->first(); 

     if($o_response === null){ 
      return false; 
     } 


    return ['value' => $o_response->values, 
      'timestamp' => $o_response->created_at]; 
} 

我想通过在刀片特定notification.thus我写的对相关联的所有值和时间戳来迭代每个循环遍历所有的值,并创建于。

@foreach($notes as $notification) 
    <?php $notificationHealth = $notes->historystatus('health'); ?> 
    <tr> 
     <td>{{ $notificationHealth['timestamp'] }}</td>       
     <td> {{ $notificationHealth['value'] }}</td>. 
    </tr>  
@endforeach 
</tbody> 

相反,它只给了我最后一个记录4次。 sql查询有问题吗?我会感谢任何建议和想法?

+0

使用$ notificationHealth = $ notification-> historystatus('health');而不是$ notificationHealth = $ notes-> historystatus('health'); –

+0

即使发生错误也会发生错误,但它不会执行作业 –

+0

为什么会用CakePHP标记?代码看起来像Laravel ... – burzum

回答

0

foreach内尝试使用$notification->historystatus('health');代替$notes->historystatus('health');

@foreach($notes as $notification) 
    <?php $notificationHealth = $notification->historystatus('health'); ?> 
    <tr> 
     <td>{{ $notificationHealth['timestamp'] }}</td>       
     <td> {{ $notificationHealth['value'] }}</td>. 
    </tr>  
@endforeach 
0
public function history($s_type) 
    { 
     if (!in_array($s_type, ['speed', 'health'])){ 
      return false; 
     } 

     $o_status = Status::where('name', strval($s_type))->first(); 
     $o_response = $this->statuses()->where('status_id', $o_status->id) 
     ->select('values', 'created_at')->orderBy('created_at','DESC')->get(); 

     if($o_response === null || $o_response->count() === 0){ 
      return false; 
     } 

     $a_ret = []; 

     foreach ($o_response as $o_status) { 
      $a_ret[] = [ 
       'value' => $o_status->values, 
       'timestamp' => $o_status->created_at 
      ]; 
     } 

     return $a_ret; 

    } 

这是简单的答案我想通了。和刀片侧边的foreach循环。

相关问题