问题:我只想在客户已经下了当年的订单的情况下获得他们。客户和订单位于两个单独的数据库中(这不能更改)。这些关系都已设置并正常工作,但是当我尝试以下操作时,我不断收到 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/