我不确定我需要做什么才能使动态表名起作用。
考虑以下模型(表“test”不存在):
<?php
// app/models/Test.php
class Test extends Eloquent {
}
然后如果我这样做(“字段”表确实存在):
<?php
// app/routes.php
$test = new \Test;
$test->setTable('fields');
$data = $test->find(1);
dd($data);
我得到一个错误:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.tests' doesn't exist (SQL: select * from `tests` where `id` = ? limit 1) (Bindings: array ( 0 => 1, ))"
请注意,从测试模型设置表名工作得很好。
L4 在 vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations.Pivot.php 构造函数中实际上使用了 setTable() 方法,非常像我想要的方式,尽管我无法得到它按照该示例进行工作。
感谢您的帮助。
最佳答案
也许这对您有用:http://laravel.io/forum/08-01-2014-defining-models-in-runtime
更准确地说,来自这里:http://laravel.io/forum/08-01-2014-defining-models-in-runtime?page=1#reply-11779
class ModelBuilder extends Eloquent {
protected static $_table;
public static function fromTable($table, $parms = Array()){
$ret = null;
if (class_exists($table)){
$ret = new $table($parms);
} else {
$ret = new static($parms);
$ret->setTable($table);
}
return $ret;
}
public function setTable($table)
{
static::$_table = $table;
}
public function getTable()
{
return static::$_table;
}
}
$user = ModelBuilder::fromTable("users")->find(1);
这不是我的最终实现,由于我的用例,它比那个更复杂(也更肮脏)。但我想这个例子可能会引导你找到你需要的东西。
关于model - 拉维尔 4 : Dynamic table names using setTable(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18044577/