model - 拉维尔 4 : Dynamic table names using setTable()

标签 model laravel eloquent

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

考虑以下模型(表“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/

相关文章:

php - Laravel Eloquent Query -> undefined variable

ruby-on-rails - 创建包含 Rails 模型的 gem

Laravel Eloquent `take` 和 `orderBy`

php - Laravel 5 PHPUnit - 从路由返回无效的 JSON

拉拉维尔 5.2 : How to access Request & Session Classes from own Event Listener?

php - Laravel Eloquent 有一个。试图获得非对象的属性

php - 在 Laravel 中使用 Eloquent 访问特定列

javascript - 从另一个组件设置模型后,Angular2 View 不更新

arrays - 在 Yii 中的数据库中插入一个数组列

methods - 需要进行多少次模拟?