使用关系和连接选择数据库行


Select database rows using relations and connection

我正在尝试使用Laravel的Eloquent 类从数据库中为我的模型选择一些数据。

我已经尝试了以下方法以更改用于test连接的数据库连接:$users = Users::on('test')->with('posts')->get();

我的数据库连接如下:(注意:唯一的区别是表前缀(prefix)

    'default' => array(
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'database',
        'username'  => 'username',
        'password'  => 'password',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),
    'test' => array(
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'database',
        'username'  => 'username',
        'password'  => 'password',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => 'test_',
    ),

问题是,当运行上面的代码($users = Users::on('test')->with('posts')->get();)时,它会运行以下SQL:

select * from `test_users`
select `posts`.*, `users_posts`.`user_id` as `pivot_user_id`, `users_posts`.`post_id` as `pivot_post_id` from `posts` inner join `users_posts` on `posts`.`id` = `users_posts`.`post_id` where `users_posts`.`post_id` in ('1', '2', '3')

在结果中没有posts,因为它从表中取posts posts而不是test_posts,依此类推,用于users_posts

在用户模型中获取用户帖子的方法如下:

public function posts() {
    return $this->belongsToMany('Users', 'users_posts', 'user_id', 'post_id');
}

这是一个错误还是我如何让它为我工作?有什么想法吗?

我在Laravel/Framework上发现了一个拉取请求,这使得设置模型关系的连接行为成为可能。

我将其集成到我的软件包中并且它起作用了。

作者给出了一些用法示例:

例子

应用程序配置:database.php

return [
    'default' => 'conn1',
    'connections' => [
        'conn1' => [ ****** ], 
        'conn2' => [ ****** ]
    ]
];

父模型

class Parent extends Eloquent
{
    public function children()
    {
        return $this->belongsTo('Child', 'parent_id', 'id');
    }
}

之前的行为:

Parent::with('children')->get();
// model Parent $connection = 'conn1';
// model Child $connection = 'conn1';

Parent::on('conn2')->with('children')->get();
// model Parent $connection = 'conn2';
// model Child $connection = 'conn1'; (default connection)

修复后:

Parent::with('children')->get();
// model Parent $connection = 'conn1';
// model Child $connection = 'conn1';
Parent::on('conn2')->with('children')->get();
// model Parent $connection = 'conn2';
// model Child $connection = 'conn1';  (default connection)
Parent::on('conn2', true)->with('children')->get();
// model Parent $connection = 'conn2';
// model Child $connection = 'conn2'; (connection of parent model)