假设我有一个通过 Commentable
实现多态的模型 Comment
。现在,如果我创建一个新的 Comment
:
$comment->commentable_type = "Post";
$comment->commentable_id = 1;
我总是可以使用 $comment->commentable();
获取 Post
。
我的问题是,如果我有一个模型的 type
和 id
,有没有一种方法可以实例化并加载该模型,而无需经历一些多态关系,例如 commentable
?
我知道在 Rails 中我可以做类似的事情:
post = "Post".constantize.where(id: 1).first
有没有办法在 PHP/Laravel 中做到这一点?
最佳答案
我确信有更好的方法,但你可以这样做并且它会起作用:
$modelType = "App\Post";
$model = new $modelType;
$model = $model->find(1);
关于php - 如何使用 id 和类型名称加载 Laravel 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36019822/