如何在laravel 4.2中动态更改模型表?

时间:2015-09-29 06:38:46

标签: php mysql database laravel laravel-4

众所周知,在创建新模型后,可以更改模型使用的表格。

例如,

$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)

1 个答案:

答案 0 :(得分:0)

上游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();