gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:32:26 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com