orm 使用join 别的数据库的表不能使用?????
ShoppingCard::query()
->with([‘shoppingCardBatches’=>function($query){
$query->select(
‘id’,
‘company’,
‘remark’,
‘end_time as batch_end_time’,
‘amount as batch_amount’,
‘gift_amount as batch_gift_amount’,
‘start_time as batch_start_time’
);
},’userShoppingCards’=>function($query){
$query->select(
‘card_id’,
‘amount as card_amount’,
‘remark as sremark’,
‘start_time as card_start_time’,
‘end_time as card_end_time’,
‘create_time as usc_time’,
‘status as card_status’,
‘lock_end_time’,
‘balance’,
‘card_type’,
‘gift_amount as card_gift_amount’
);
}])
->joinSub($walkingVoucher, ‘walking_voucher’, function ($join) {
$join->on(‘shopping_cards.batch_id’, ‘=’, ‘walking_vouchers.shopping_card_batches_id’);
})
//->join(‘mysql.walking_vouchers’,’walking_vouchers.shopping_card_batches_id’,’=’,’shopping_cards.batch_id’)
->when(!empty($params[‘card_id’]),function ($query)use ($params){
$query->where(‘shopping_cards.id’,’like’,’%’.$params[‘card_id’].’%’);
})
->when(!empty($params[‘card_status’]),function ($query)use ($params){
$query->whereHas(‘userShoppingCards’,function ($query)use ($params){
$query->where(‘status’,$params[‘card_status’]);
});
})
->select(
‘shopping_cards.id’,
‘shopping_cards.batch_id’,
‘shopping_cards.id as card_id’,
‘shopping_cards.password’,
‘shopping_cards.user_id’,
‘shopping_cards.status as card_base_status’,
‘shopping_cards.end_time as custom_end_time’
)
// ->orderByDesc(‘walking_vouchers.create_time’)
->paginate($params[‘limit’]??20); orm 使用join 别的数据库的表不能使用?????
本作品采用《CC 协议》,转载必须注明作者和本文链接
chatGPT
在 Laravel 的 Eloquent ORM 中,跨数据库 JOIN 可以通过定义关联关系并使用查询构建器实现。以下是一个示例:
首先,我们需要创建两个模型,分别对应两个数据库中的表。这里假设我们有两个数据库
db1
和db2
,以及两个表table1
和table2
。app/Models
目录下创建一个名为Table1
的模型:Copy
这里,我们将模型
Table1
的数据库连接设置为db1
,并定义了一个关联关系table2()
,表示在table2
中有一个与table1
相关联的记录。app/Models
目录下创建一个名为Table2
的模型:Copy
这里,我们将模型
Table2
的数据库连接设置为db2
,并定义了一个关联关系table1()
,表示在table1
中有一个与table2
相关联的记录。config/database.php
中定义了这两个数据库连接:Copy
Copy
这将执行跨数据库 JOIN 查询,并获取
table1
和table2
中的相关记录。你可以根据需要修改查询条件和返回的字段。Regenerate response
分不同的服务器连接, 已经应用到了多个项目实际运行半年有余