为了更好地解释这一点,这是我的代码:
$mydate=Carbon::now()->addHours(8);
$newdate=$mydate->toDateString();
$myquery = DB::table('attendances')->where('date_only', '=', $newdate)->orderBy('logon','asc')->get();
$counter=0;
foreach ($myquery as $newquery)
{
$query1[$counter]=$newquery->user_id;
$finalquery[$counter]= DB::table('employees')->where('id', '=', $query1[$counter])->get();
$counter++;
}
var_dump($finalquery[2]);
此代码的输出将是这样的:
array(1) { [0]=> object(stdClass)#160 (6) { ["id"]=> int(23) ["firstname"]=> string(3) "Kim" ["lastname"]=> string(7) "Samsung" ["position"]=> string(10) "Programmer" ["created_at"]=> string(19) "2014-11-25 07:21:31" ["updated_at"]=> string(19) "2014-11-25 07:21:31" } }
我想做的是访问它的值之一,所以我尝试了这个
//I change
var_dump($finalquery[2]);
//to this
var_dump($finalquery[2]->firstname);
但我得到的只是错误。错误代码 500
试试这个
// not necessary
foreach ($myquery as $key => $newquery)
{
$query1[$key]=$newquery->user_id;
$finalquery[$key]= DB::table('employees')->where('id', '=', $query1[$key])->get();
}
// necessary
print_r($finalquery->toArray()); // if its array of objects I'm converting it into an array
// or
print_r($finalquery);
编辑:伙计我的建议是使用joins
这个单一的查询将为你提供所有数据,不需要使用一个foreach
与多个查询
$myquery = DB::table('attendances')->select('employees.id as emp_id','attendances.id as att_id',/*your fields*/)
->leftJoin('employees', 'employees.id','=','attendances.id')
->where('date_only', '=', $newdate)
->orderBy('attendances.logon','asc')->get();
print_r($myquery->toArray());
在控制器中
return View::make('home', array('mydata' => $finalquery));
视野:(用于刀片)
@if($mydata && count($mydata) > 0)
@foreach($mydata as $data)
{{ $data->id }}<br>
{{ $data->name }}<br>
{{ $data->etc }}<br>
@endforeach
@else
<p>sorry no data to display</p>
@endif
您的var_dump
表明finalquery[2]
是一个对象数组,而不是对象本身。所以这行不通
var_dump($finalquery[2]->firstname);
这将
var_dump($finalquery[2][0]->firstname);
喜欢
foreach($finalquery[2] as $obj)
{
echo $obj->firstname;
}