Php 使用laravel 5.1中的hasManyThrough关系的模型的不同db连接
我试图在laravel 5.1中使用hasManyThrough关系,但是sql查询没有使用在每个连接中为所使用的每个模型定义的适当前缀。 我有3个型号,其中2个使用相同的连接,其中一个使用不同的连接。连接之间的唯一区别是数据库的前缀相同Php 使用laravel 5.1中的hasManyThrough关系的模型的不同db连接,php,mysql,laravel-5,eloquent,query-builder,Php,Mysql,Laravel 5,Eloquent,Query Builder,我试图在laravel 5.1中使用hasManyThrough关系,但是sql查询没有使用在每个连接中为所使用的每个模型定义的适当前缀。 我有3个型号,其中2个使用相同的连接,其中一个使用不同的连接。连接之间的唯一区别是数据库的前缀相同 模型A具有使用前缀A的连接A_ 型号B具有使用前缀B的连接B_ 型号C具有使用前缀B的连接B_ 关系: B型车内: public function relationshipWithA() { return $this->hasManyThro
- 模型A具有使用前缀A的连接A_
- 型号B具有使用前缀B的连接B_
- 型号C具有使用前缀B的连接B_
public function relationshipWithA()
{
return $this->hasManyThrough(A::class, C::class, 'Cid', 'Aid');
}
最终的查询逻辑是正确的,但不是对联接的表使用B_uu前缀,而是对查询中的所有表使用A_uu前缀
这是laravel的缺陷/限制吗?是否有解决方案,否则我将不得不执行手动连接以实现我想要的功能?其他关系类型适用于多个数据库连接:
public function foos()
{
return $this->belongsToMany(Foo::class, 'other_db.foos');
}
但是hasManyThrough
的签名中没有$table
参数,因此相同的解决方案不适用
但是,
您可以创建一个不完美的解决方案,如下所示:
public function bars()
{
return $this->belongsToMany(Bar::class, 'other_db.bars');
}
public function foos()
{
$barIds = $this->bars->pluck('id');
return Foo::whereIn('bar_id', $barIds);
}
protected $appends = [
'foos',
];
/**
* @return Foo[]
*/
public function getFoosAttribute()
{
return $this->foos()->get();
}
它不提供完全相同的功能(因为它是一种不同的返回类型),但满足了更简单的目的
如果需要,还可以通过执行以下操作复制更多语法:
public function bars()
{
return $this->belongsToMany(Bar::class, 'other_db.bars');
}
public function foos()
{
$barIds = $this->bars->pluck('id');
return Foo::whereIn('bar_id', $barIds);
}
protected $appends = [
'foos',
];
/**
* @return Foo[]
*/
public function getFoosAttribute()
{
return $this->foos()->get();
}
这样,您仍然可以在代码中使用它,就像大多数时候使用常规关系一样(这意味着您可以使用
$this->foos
而不是$this->foos()->get()
)实际上,如果您通过$connection
属性指定模型类中的连接,它似乎工作得很好。我在MySQL和SQL连接之间使用morphMany关系测试了它(Laravel 5.5):
账户模式:
class Account extends Model
{
protected $connection = 'sqlsrv';
public function notifications()
{
return $this->morphMany(Notification::class, 'notifiable');
}
}
通知模式:
class Notification extends Model
{
protected $connection = 'mysql';
public function notifiable()
{
return $this->morphTo();
}
}
laravel模型将不适用于关系的不同连接,因为Elounce在幕后使用SQL连接,这在多个DB连接中是不可能的。它可能适用于多个数据库连接,但这个问题是关于hasManyThrough的,它不起作用。