我有这个控制器可以在多对多的关系中访问数据透视表。数据透视表中的列是值和created_at。我希望这个控制器返回一个值数组和created_at
public function status($s_type)
{
$o_health_status = Status::where('name', 'health')->first();
$o_speed_status = Status::where('name', 'speed')->first();
if ($s_type === 'health'){
$o_response = $this->statuses()->where('status_id', $o_health_status->id)
->select('values','created_at')->orderBy('created_at','ASC')->first();
if($o_response === null){
return 'unsigned';
}
$o_response = $o_response->values;
return $o_response;
}else{
$o_response = $this->statuses()->where('status_id', $o_speed_status->id)
->select('values','created_at')->orderBy('created_at', 'desc')->first();
if($o_response === null){
return 'unsigned';
}
$o_response = $o_response->values;
return $o_response;
}
答案 0 :(得分:1)
你需要使用pluck。这将从集合中获取所有必需的元素:所以我清理了一下,应该看起来像这样:
public function status($s_type)
{
$o_health_status = Status::where('name', 'health')->first();
$o_speed_status = Status::where('name', 'speed')->first();
$o_response = $s_type === 'health' ? $this->statuses()->pluck('values','created_at')->where('status_id', $o_health_status->id)
->select('values', 'created_at')->orderBy('created_at', 'asc')->first() : $this->statuses()->pluck('values','created_at')->where('status_id', $o_speed_status->id)
->select('values', 'created_at')->orderBy('created_at', 'desc')->first();
return ! $o_response ? 'unsigned' : $o_response->values;
}
答案 1 :(得分:0)
在laravel中,如果您需要从查询中返回数组,则可以使用pluck()
代替select()
$o_response = $this->statuses()->where('status_id', $o_health_status->id)
->pluck('values','created_at')->orderBy('created_at','ASC');// ->first();
//I think you no need to use ->first(); here.
Docs(向下滚动到检索列值列表)