本文介紹了通過字符串調(diào)用 Laravel 模型的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
是否可以通過字符串調(diào)用 Laravel 模型?
Is it possible to call a Laravel model by string?
這就是我想要實現(xiàn)的目標,但它失敗了:
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();
如果您的模型名稱存儲在普通變量以外的其他內(nèi)容(例如對象屬性)中,您將需要使用中間變量才能使其工作.
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();
這篇關(guān)于通過字符串調(diào)用 Laravel 模型的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!