我已正确设置与两个数据库的连接。我还创建了雄辩的表模型,我可以轻松地从另一个数据库查询单个表关系,例如
$user->customer
用户模型
class User extends Model
{
protected $connection = 'mysql';
protected $table = 'users';
public function customer()
{
return $this->hasMany(Customer::class, 'user_id', 'id');
}
}
客户模型
class Customer extends Model
{
protected $connection = 'second_db';
protected $table = 'customers';
public function order()
{
return $this->hasMany(Order::class, 'customer_id', 'id');
}
}
我可以使用这个简单的查询获取第二个数据库中的订单数据
$customer->order
但是当使用第一个数据库查询时它给出空结果
$user->customer->order
or
$user->customer()->order
如何从第一个dB查询得到第二个dB的关系数据?
在急切加载时,您可能需要指定底层
Illuminate\Database\Query\Builder
对象内部的连接。
$customers = Customer::query()
->with([
'order' => function (HasMany $relation) {
$eloquentBuilder = $relation->getQuery();
$baseBuilder = $eloquentBuilder->getQuery();
$baseBuilder->connection = DB::connection('mysql');
},
])
->get();
将此应用于嵌套关系:
$user = User::query()
->with(['customers' => function (HasMany $customers_relation) {
$customers_relation
->getQuery()
->getQuery()
->connection = DB::connection('second_db');
$relation->with(['orders' => function (HasMany $orders_relation) {
$orders_relation
->getQuery()
->getQuery()
->connection = DB::connection('mysql');
}]);
}])
...
->first();