Laravel 4:使用setTable()的动态表名

T.O*_*.O. 2 model laravel eloquent

我不确定我需要做什么才能使动态表名起作用.

考虑以下模型(表'test'不存在):

<?php

// app/models/Test.php

class Test extends Eloquent {

}
Run Code Online (Sandbox Code Playgroud)

如果我这样做('fields'表确实存在):

<?php

// app/routes.php

$test = new \Test;
$test->setTable('fields');
$data = $test->find(1);
dd($data);
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

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, ))"
Run Code Online (Sandbox Code Playgroud)

请注意,从Test模型设置表名称可以正常工作.

L4实际上使用了setTable()方法,非常类似于我想要的方式,在vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations.Pivot.php构造函数中,虽然我无法让它工作遵循那个例子.

感谢帮助.

Dan*_*rin 7

也许这对你有用: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);
Run Code Online (Sandbox Code Playgroud)

这不是我的最终实现,因为我的用例,它比那更复杂(也更脏).但我想这个例子可能会引导您达到您的需求.