Kim*_*kis 8 php mysql query-builder eloquent laravel-5
我试图在laravel 5.1中使用hasManyThrough关系,但sql查询没有使用每个连接中为每个使用的模型定义的适当前缀.我有3个模型2其中使用相同的连接,其中一个使用不同的连接.连接之间的唯一区别是数据库的前缀相同.
关系:
B型内部:
public function relationshipWithA()
{
return $this->hasManyThrough(A::class, C::class, 'Cid', 'Aid');
}
Run Code Online (Sandbox Code Playgroud)
最终查询逻辑是正确的,但不是对连接表使用B_前缀,而是使用查询中所有表的A_前缀.
这是laravel的错误/限制吗?有没有解决方案,或者我必须手动加入以实现我想要的?
其他关系类型适用于多个数据库连接:
public function foos()
{
return $this->belongsToMany(Foo::class, 'other_db.foos');
}
Run Code Online (Sandbox Code Playgroud)
但其签名中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);
}
Run Code Online (Sandbox Code Playgroud)
它不提供完全相同的功能(因为它是不同的返回类型),但满足了更简单的事情的目的。
如果需要,您还可以通过执行以下操作来复制更多语法:
protected $appends = [
'foos',
];
/**
* @return Foo[]
*/
public function getFoosAttribute()
{
return $this->foos()->get();
}
Run Code Online (Sandbox Code Playgroud)
这样您仍然可以在代码中使用它,就像大多数时候在常规关系中一样(这意味着您可以使用$this->foos而不是$this->foos()->get())