本文介紹了通過字符串調用 Laravel 模型的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
是否可以通過字符串調用 Laravel 模型?
Is it possible to call a Laravel model by string?
這就是我想要實現的目標,但它失敗了:
This is what i'm trying to achieve but its failing:
$model_name = 'User';
$model_name::where('id', $id)->first();
我收到以下異常:
exception 'ErrorException' with message 'Undefined variable: User'
推薦答案
是的,您可以這樣做,但您需要使用完全限定的類名:
Yes, you can do this, but you need to use the fully qualified class name:
$model_name = 'AppModelUser';
$model_name::where('id', $id)->first();
如果您的模型名稱存儲在普通變量以外的其他內容(例如對象屬性)中,您將需要使用中間變量才能使其工作.
If your model name is stored in something other than a plain variable (e.g. a object attribute), you will need to use an intermediate variable in order to get this to work.
$model = $this->model_name;
$model::where('id', $id)->first();
這篇關于通過字符串調用 Laravel 模型的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!