php - 错误:试图获取非对象的属性
问题描述
我创建了一个数据库助手来减少我在 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
视图时,您应该:
@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。这需要更多时间,但会大大加快您的应用程序的生产过程。
推荐阅读
- javascript - 当模式关闭时,转到 React 中的上一个 url
- scala - 为什么在使用混合项目时,Java 类中的 Scala 案例类中的 Lombok 无法访问?
- python - 如何将字符串添加到字典的每个键?
- javascript - 如何将多个 *ngIf 与 && 运算符结合使用,并以角度形式显示?
- php - POST 变量 - XHTTP、PHP
- android - 如何使用 Appium 访问 Android 微调器中的元素?
- python - 这个特定的 Python 递归是如何工作的?为什么结果值会变成 1、3、6、10、15、21?
- javascript - 一个数字数组和一个数学符号数组变成一个数学表达式?
- android - 新版 Android Studio 的问题(看不到 ConstraintLayout 和其他视图,manifest 中的一些活动......)
- javascript - webrtc上的屏幕共享(如何添加到跟踪?)