我正在尝试使用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');
}
这是一个错误还是我怎么能让它为我工作?有什么想法吗?
答案 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)