我正在尝试从表中检索某些值,但在尝试将结果作为Fluent返回的对象的属性访问时遇到Unhandled exception: Trying to get property of non-object
错误。
问题:尝试访问对象的属性有效,即使它抛出错误。这对我来说真是令人费解。可能是什么问题?
PHP代码
$sets = DB::table('sets')->where('user_id', '=', $user_id)->get();
// Get thumbnail of latest item added to set
foreach($sets as $set) {
$post_set = DB::table('posts_sets')
->where('set_id', '=', $set->id)
->order_by('created_at', 'desc')
->first();
print_r($post_set); // works fine
echo $post_set->id; // prints out value, BUT throws the unhandled exception error!
}
Trying to get property of non-object
/home/test/public_html/application/controllers/api.php on line 47
#0 /home/test/public_html/laravel/laravel.php(40): Laravel\Error::native(8, 'Trying to get p...', '/home/test/pub...', 47) #1 /home/test/public_html/application/controllers/api.php(47): Laravel{closure}(8, 'Trying to get p...', '/home/test/pub...', 47, Array) #2 [internal function]: Api_Controller->action_sets() #3 /home/test/public_html/laravel/routing/controller.php(323): call_user_func_array(Array, Array) #4 /home/test/public_html/laravel/routing/controller.php(283): Laravel\Routing\Controller->response('sets', Array) #5 /home/test/public_html/laravel/routing/controller.php(165): Laravel\Routing\Controller->execute('sets', Array) #6 /home/test/public_html/laravel/routing/route.php(153): Laravel\Routing\Controller::call('api@(:1)', Array) #7 /home/test/public_html/laravel/routing/route.php(124): Laravel\Routing\Route->response() #8 /home/test/public_html/laravel/laravel.php(125): Laravel\Routing\Route->call() #9 /home/test/public_html/public/index.php(34): require('/home/test/pub...') #10 {main}
答案 0 :(得分:2)
首先,如果数据库中没有可用的数据记录,$ post_set查询将返回NULL,这意味着您应该首先检查is_null($ post_set)。
答案 1 :(得分:0)
你应该使用雄辩来做到这一点。
请记住,您正在foreach中进行查询,当数据库变大时,您将遇到性能问题。
使用eloquent你可以像这样使用急切加载:
$sets = Set::with('posts')->where_user_id($user_id)->get();
foreach($sets as $set)
{
var_dump($set);
var_dump($set->posts);
}
中查看更多内容