Php 如何使用id和类型名称加载Laravel模型?
假设我有一个通过Php 如何使用id和类型名称加载Laravel模型?,php,laravel,model,eloquent,polymorphism,Php,Laravel,Model,Eloquent,Polymorphism,假设我有一个通过Commentable多态的模型Comment。现在,如果我用以下内容创建一个新的注释: $comment->commentable_type = "Post"; $comment->commentable_id = 1; 我总是可以使用$comment->commentable()获得帖子 我的问题是,如果我有一个模型的类型和id,有没有一种方法可以实例化和加载该模型而不必经历一些多态关系,比如可注释的 我知道在Rails中,我可以做一些类似的事情: post =
Commentable
多态的模型Comment
。现在,如果我用以下内容创建一个新的注释
:
$comment->commentable_type = "Post";
$comment->commentable_id = 1;
我总是可以使用$comment->commentable()获得帖子
代码>
我的问题是,如果我有一个模型的类型
和id
,有没有一种方法可以实例化和加载该模型而不必经历一些多态关系,比如可注释的
我知道在Rails中,我可以做一些类似的事情:
post = "Post".constantize.where(id: 1).first
在PHP/Laravel中有这样做的方法吗?我相信有更好的方法,但您可以这样做,并且它会起作用:
$modelType = "App\Post";
$model = new $modelType;
$model = $model->find(1);
use App\Post;
class Comment extends Controller
{
public function findId()
{
$post = Post::find(1);
return $post;
}
}