php - Laravel whereHas 跨两个独立的数据库

标签 php laravel laravel-4 eloquent relationship

问题:我只想在客户已经下了当年的订单的情况下获得他们。客户和订单位于两个单独的数据库中(这不能更改)。这些关系都已设置并正常工作,但是当我尝试以下操作时,我不断收到 SQL 错误,因为它试图在“客户”数据库中搜索“订单”。无论如何强制 Laravel 在这种情况下使用正确的数据库?

$customers = $customers->whereHas('orders', function($query){
    $query->where('academic_year_id', '=', $this->current_academic_year->id);
});

$customers = $customers->orderBy('DFKEY','ASC')->get();

订购型号:

public function customer()
{
    return $this->belongsTo('Customer','dfkey');
}

客户模型:

protected $connection = 'mysql2';

public function orders()
{
    return $this->hasMany('Order','dfkey','DFKEY');
}

提前致谢!

最佳答案

晚会迟到了,但对于其他有类似问题的人来说,下面的方法应该有效(只要两个数据库都在一台服务器上)。

显式设置连接和表。

protected $connection = 'mysql2';
protected $table_name = 'mysql2.orders';

或者如果您愿意 - 像这样动态设置表格:

protected $table = 'orders';
public function __construct() {
    $this->table = DB::connection($this->connection)->getDatabaseName() . '.' . $this->table_name;
}

甚至

public function __construct() {
    $this->table = DB::connection($this->connection)->getDatabaseName() . '.' . $this->getTable();
}

关于php - Laravel whereHas 跨两个独立的数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27394675/

相关文章:

php - 切换协议(protocol)时 Laravel session 不工作(https 到 http 或 http 到 https)

php - 使用 PHP 设置选定的选项值

php - 如何使用 mysql 中的连接从一个表中选择一行并从另一个表中选择多行,

php - mysql_fetch_array() & mysql_free_result() 错误

php - PHP 有线程吗?

php - Laravel 计算列值为 1 的行

javascript - 使用 laravel 从 json 中删除 &quot

php - 关系的 Eloquent 查询范围

拉拉维尔 4 : loading an old library: how?

php - 模型事件没有触发