项目中有2个数据库,现在想关联report库中的tb_deposit_appstore表和gamesnapshot库中的tb_commodity_snapshot表
database.php里的collection配置如下
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '192.168.0.202'),
'database' => env('DB_DATABASE', 'report'),
'username' => env('DB_USERNAME', 'xx'),
'password' => env('DB_PASSWORD', '123456'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
'mysql_snapshot' => [
'driver' => 'mysql',
'host' => env('DB_HOST_SNAPSHOT', '192.168.0.236'),
'database' => env('DB_DATABASE_SNAPSHOT', 'gamesnapshot'),
'username' => env('DB_USERNAME_SNAPSHOT', 'xx'),
'password' => env('DB_PASSWORD_SNAPSHOT', '123456'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
// 'prefix' => 'tb_',
'strict' => false,
],
查询构造器代码如下
$data = CommodityModel::select('tb_commodity_snapshot.*')
->join('report.tb_deposit_appstore','tb_deposit_appstore.id','=','tb_commodity_snapshot.commodity_id')
->get();
tb_commodity_snapshot表的model代码如下:
<?php
namespace App\Models\Report;
use Illuminate\Database\Eloquent\Model;
class Commodity extends Model
{
/**
* 限制读取字段
*
* @var array
*/
protected $guarded = [];
/**
* config/database配置中指定连接库名
*
* @var string
*/
protected $connection = 'mysql_snapshot';
/**
* 设置模型表名
*
* @var string
*/
protected $table = "tb_commodity_snapshot";
public function depositAppstore()
{
return $this->belongsTo('App\Models\Game\DepositAppstore','commodity_id');
}
public function depositCommodity()
{
return $this->belongsTo('App\Models\Game\DepositCommodity','commodity_id');
}
}
tb_deposit_appstore表的model配置如下
<?php
namespace App\Models\Game;
use Illuminate\Database\Eloquent\Model;
class DepositAppstore extends Model
{
/**
* 限制读取字段
*
* @var array
*/
protected $guarded = [];
protected $connection = 'mysql';
/**
* 设置模型表名
*
* @var string
*/
protected $table = "tb_deposit_appstore";
}
错误信息:
QueryException in Connection.php line 729:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'report.tb_deposit_appstore' doesn't exist (SQL: select `tb_commodity_snapshot`.* from `tb_commodity_snapshot` inner join `report`.`tb_deposit_appstore` on `tb_deposit_appstore`.`id` = `tb_commodity_snapshot`.`commodity_id`)
目前尝试过在depositAppstore的model里面设置表名为
protected $table = "report.tb_deposit_appstore";
但是没什么卵用。。估计是因为join的时候直接写死表名了,上述错误应该是主查询仍在gamesnapshot库中查询,求问大神如何关联到report库中的表?