且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel 5动态创建雄辩模型

更新时间:2023-01-29 13:54:19

首先, latestRevision RevisionableTrait 添加的关系,因此您需要确保 Dynamic 类具有 use RevisionableTrait; 语句.

First, latestRevision is a relationship added by the RevisionableTrait, so you need to make sure that your Dynamic class has the use RevisionableTrait; statement.

接下来,由于 find()方法(以及任何其他检索方法)将返回模型的新实例,因此,找到模型后,您将需要在每个模型上再次重置表.因此,您的代码应类似于:

Next, since the find() method (and any other retrieval methods) return new instances of the models, you will need to reset the table again on every model after you find it. So, your code would look something like:

$model = new Dynamic([]);
$model->setTable($row['table_name']);
$model = $model->find($row['row_id']);
$model->setTable($row['table_name']);
$revision = $model->latestRevision;


假设您遵循Laravel的命名约定,另一种选择是可以从table_name确定 Model 名称,而从一开始就使用正确的 Model Dynamic 模型的模型:


Another option, assuming you follow Laravel's naming conventions, is that you could determine the Model name from the table_name, and just use the correct Model from the start, instead of this Dynamic model:

$modelName = Str::studly(Str::singular($row['table_name']));
$model = $modelName::find($row['row_id']);
$revision = $model->latestRevision;