簡體   English   中英

在null上調用成員函數getmetavalue()

[英]Call to a member function getmetavalue() on null

當模型的函數調用數據庫表為空時,出現錯誤。 這是我在AccountMeta模型中的代碼。

public function scopeGetmetavalue($query, $key){
    $data = $query->where('meta_key', '=', $key)->pluck('meta_value');
    if($data->count()){
        if(isset($data[0])){
            return $data[0];
        }
    }

    return " ";
}

我認為這是這樣的:

$GroupFile = Auth::user()->account->meta->getmetavalue('file_group_contact');

我的數據庫結構是這樣的:

Schema::create('account_metas', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('account_id');
            $table->string('meta_key');
            $table->string('meta_value');
            $table->timestamps();
        });

當account_metas表中有數據時沒有問題,但是當它為空時我得到了錯誤。 有什么想法嗎?

當表中沒有數據時, Auth::user()->account->meta將返回null 所以打給

Auth::user()->account->meta->getmetavalue('file_group_contact')

當您在null上調用getmetavalue() ,必然會給您一個異常 如果只想忽略Exception ,則在語句前加上@符號:

 $GroupFile =  @Auth::user()->account->meta->getmetavalue('file_group_contact');

現在,當table沒有數據時,您將$GroupFilenull而不是獲取異常。 然后,您可以在執行代碼之前檢查$GroupFile的值。

if($GroupFile) {
 // some code
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM