0

我正在尝试从表中检索一些值,但Unhandled exception: Trying to get property of non-object在尝试将结果作为 Fluent 返回的对象的属性进行访问时出现错误。

问题:尝试访问对象的属性有效,即使它抛出错误。这对我来说真的很令人费解。可能是什么问题?

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!
}

错误

未处理的异常

信息:

试图获取非对象的属性

地点:

/home/test/public_html/application/controllers/api.php 在第 47 行

堆栈跟踪:

#0 /home/test/public_html/laravel/laravel.php(40): Laravel\Error::native(8, '尝试获取 p...', '/home/test/pub...', 47 )
        #1 /home/test/public_html/application/controllers/api.php(47): Laravel{closure}(8, '试图获取 p...', '/home/test/pub...', 47 , 大批)
        #2【内部函数】: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 {主要}

4

2 回答 2

2

首先,如果数据库中没有可用的数据记录,$post_set 查询将返回 NULL,这意味着您应该始终首先检查 is_null($post_set)。

于 2012-07-24T14:21:17.570 回答
0

你应该使用 eloquent 来做到这一点。

请记住,您是在 foreach 中进行查询,当您的数据库变大时,您会遇到性能问题。

使用 eloquent 你可以像这样使用急切加载:

$sets = Set::with('posts')->where_user_id($user_id)->get();

foreach($sets as $set)
{
var_dump($set);
var_dump($set->posts);
}

你可以在http://laravel.com/docs/database/eloquent看到更多

于 2013-02-19T18:08:36.240 回答