laravel 覆盖模型的表前缀

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42394101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:23:54  来源:igfitidea点击:

Override table prefix for a model

laraveleloquentlaravel-5.2

提问by natas

Hello I've in config/database.php a prefix (mysql) like this:

你好,我在 config/database.php 中有一个这样的前缀(mysql):

     'prefix' => 'myprefix_',

But I need, only for one model, to use a different prefix like:

但我只需要对一个模型使用不同的前缀,例如:

     protected $table = 'otherprefix_mytable';

In this way laravel looking for "myprefix_otherprefix_mytable".

通过这种方式,laravel 寻找“myprefix_otherprefix_mytable”。

Any help?

有什么帮助吗?

回答by KuKeC

In your app/config/database.phpmake 2 different connections like

在您建立app/config/database.php2 个不同的连接时,例如

'connections' => array(

        # first prefix
        'mysql1' => array(
            'driver'    => 'mysql',
            'host'      => 'host1',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => 'prefix1',
        ),

        # second prefix
        'mysql2' => array(
            'driver'    => 'mysql',
            'host'      => 'host1',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => 'prefix2',
        ),
    ),

And then later in model you can use different connection

然后在模型中你可以使用不同的连接

class SomeModel extends Eloquent {    
    protected $connection = 'mysql2';    
}

For more help check this

如需更多帮助,请检查

回答by Samsher

Default table prefix can be overriding in laravel model as following example:

可以在 laravel 模型中覆盖默认表前缀,如下例所示:



public function __construct(array $attributes = array()) {
    $colletion = Config::get('database');
    $collection['connections']['mysql']['prefix'] = 'consultancy_';
    Config::set('database',$collection);
    parent::__construct($attributes);
}