为什么设置的连接在嵌套关系中不起作用?
Follower.php
class Follower extends Model {
$connection = 'followers';
public function details() {
return $this->belongsTo(User::class, 'user_id');
}
}
User.php
class User extends Model {
$connection = 'users';
protected $withCount = ['notifications'];
public function notifications() {
return $this->setConnection('followers')->hasMany('App\Models\Notifications');
}
}
和查询:
Follower::query()->where('user_id', 1)->with('details')->get();
它抛出:
SQLSTATE [42S02]:未找到基表或视图:1146表 'users.notifications'不存在(SQL:选择`....
但是当我尝试它的时候效果很好
User::with('notifications')->find(1);
更新 Notification.php
class Notification extends Model
{
protected $fillable = [
'user_id',
'builder',
'notification_type',
'comment_id',
'read_at'
];
}
答案 0 :(得分:1)
这是laravel自2018年以来的一个已知问题,有关更多信息,请参见此thread,还有一个open pull request可以解决此问题,并将在下一版本中得到解决
现在您可以使用hoyvoy/laravel-cross-database-subqueries软件包
使用此安装软件包
composer require hoyvoy/laravel-cross-database-subqueries
Follower.php
use Hoyvoy\CrossDatabase\Eloquent\Model;
class Follower extends Model {
$connection = 'followers';
public function details() {
return $this->belongsTo(User::class, 'user_id');
}
}
User.php
use Hoyvoy\CrossDatabase\Eloquent\Model;
class User extends Model {
$connection = 'users';
protected $withCount = ['notifications'];
public function notifications() {
return $this->setConnection('followers')->hasMany('App\Models\Notifications');
}
}
为每个模型添加默认的protected $connection