[英]Error of : Trying to get property of non-object
我创建了一个数据库助手来减少我在laravel框架中的代码,并连接到两个数据库但是当我在我的帮助器中使用该函数时,我收到错误消息“试图获取非对象的属性”,这是我的帮助代码:
/**
* This function Used for get Data For Specific Element.
*/
public static function getDataById($dbName,$tableName,$condition,$data)
{
$stattment=
DB::connection($dbName)
->table($tableName)
->select(['*'])
->where($condition, $data)
->first();
return $stattment;
}
这是我的控制器功能
public function all()
{
$dataView['x']=dBHelper::allData('mysql',
'products',
'`status`=? AND `deleted`=?'
,array(1,1));
if(is_object($dataView['x']))
{
foreach ($dataView['x'] as $key=>$value):
$dataView['lang'][$key]=dBHelper::getDataById(
'mysql2',
'products',
'id_product',
$value->id);
//var_dump($dataView['lang'][$key]);
endforeach;
}
return view('productss.all',$dataView);
}
这是我的看法
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
</h1>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-lg-12">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title ">Show Products</h3>
</div>
<!-- /.box-header -->
<div class="adminform">
<!-- form start -->
<table id="all_data" class="table table_for_data table-striped table-bordered dt-responsive nowrap tableData" cellspacing="0" width="100%">
<thead>
<tr>
<th>Id</th>
<th>User Name</th>
</tr>
</thead>
<tbody>
@if(isset($x)&&is_object($x))
@foreach($x as $key=>$value)
<tr>
<td>{{$value->id}}</td>
<td>{{$lang[$key]->name}}</td>
</tr>
@endforeach
@else
<td>no data found</td>
@endif
</tbody>
</table>
</div>
</div>
<!-- /.box -->
</div>
</div>
</section><!-- /.content -->
</div><!-- /.content-wrapper -->
我打印时收到错误
<td>{{$lang[$key]->name}}</td>
谢谢。
当您将$dataView
返回给View时,您应该:
@if(isset($dataView['x']) && is_object($dataView['x']))
@foreach($dataView['x'] as $key=>$value)
<tr>
<td>{{$value->id}}</td>
<td>{{$value['lang'][$key]->name}}</td>
</tr>
@endforeach
@else
<td>no data found</td>
@endif
希望这可以帮助。 另一方面,像您这样的快捷方式使调试变得困难,或者在将来的某个日期进行扩展。 最好建立模型及其关系,从而利用Laravel的原生ORM。 这需要更多时间,但会大大加快应用程序的制作过程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.