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

时间:2014-12-08 13:59:16

标签: php laravel laravel-4 eloquent

我正在尝试使用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');
}

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

1 个答案:

答案 0 :(得分:0)

我在pull request上找到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)