【问题标题】:How to change table of model dynamically in laravel 4.2?如何在 laravel 4.2 中动态更改模型表?
【发布时间】:2015-12-26 12:53:18
【问题描述】:

众所周知,新建模型后,有一个函数可以改变模型使用的表。

例如,

$example_model = new ExampleModel;
$example_model->setTable('myTable_'.$some_other_variable);

但是,如果我从表中查找记录,有没有办法在查询数据库之前选择表?

即像这样的

$example_model = ExampleModel::setTable('myTable_'.$some_other_variable)->where('myColumn', $variable_to_be_compared)->get();

(注意到下面这行不正确。我会说 setTable 不是静态方法)

我的模型中有一些自定义函数,所以我不想使用DB::table('myTable_'.$some_other_variable)

【问题讨论】:

    标签: php mysql database laravel laravel-4


    【解决方案1】:

    上游 setTable() 方法的问题在于它不返回任何内容 (void),因此即使您设法调用它,也无法将其与其他方法链接,除非您覆盖它。

    // File: ExampleModel.php
    /**
     * Set the table associated with the model.
     *
     * @param  string  $table
     * @return self
     */
    public function setTable($table)
    {
        $this->table = $table;
        return $this;
    }
    

    然后你可以做这样的事情

    $example_model = with(new ExampleModel)->setTable('myTable_'.$some_other_variable)->where('myColumn', $variable_to_be_compared)->get();
    

    但由于该解决方案涉及编写方法,因此您可以为该任务编写一个新的静态方法,这样您就不需要使用帮助程序

    /**
    * Change the table associated with the model.
    *
    * @param  string  $table
    * @param  array   $attributes
    * @return self
    */
    public static function changeTable($table, $attributes = [])
    {
        $instance = new static($attributes);
        $instance->setTable($table);
    
        return $instance;
    }
    

    哪个可以用

    $example_model = ExampleModel::changeTable('myTable_'.$some_other_variable)->where('myColumn', $variable_to_be_compared)->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-05
      • 1970-01-01
      • 2017-05-13
      • 1970-01-01
      • 1970-01-01
      • 2017-10-08
      • 2016-02-26
      • 1970-01-01
      相关资源
      最近更新 更多