如何使用 id 和类型名称加载 Laravel 模型


How do I load a Laravel Model using id and type name?

假设我有一个通过Commentable Comment多态的模型。 现在,如果我创建一个新Comment

$comment->commentable_type = "Post";
$comment->commentable_id = 1;

我总是可以使用$comment->commentable();获得Post

我的问题是,如果我有一个模型的typeid有没有办法实例化和加载该模型,而无需经历像commentable这样的多态关系?

我知道在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;
  }
}