【问题标题】:Laravel nested cross database relationLaravel 嵌套跨数据库关系
【发布时间】:2020-08-03 17:57:37
【问题描述】:

为什么设置连接在嵌套关系中不起作用?

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: select ` ....

但是当我尝试这个时效果很好

User::with('notifications')->find(1);

更新 Notification.php

class Notification extends Model
{
    protected $fillable = [
        'user_id',
        'builder',
        'notification_type',
        'comment_id',
        'read_at'
    ];
}

【问题讨论】:

  • user.php 已更新
  • @iamab.in 结果还是一样
  • 您的 details 方法在 user_id 中缺少关闭引号,这是 stackoverflow 或代码中的错字吗??
  • @bhucho,抱歉,代码更新了,这是 stackoverflow 上的一个错误
  • 你能添加App\Models\Notifications类吗?

标签: laravel eloquent relationship relation


【解决方案1】:

这是自 2018 年以来 laravel 的一个已知问题,有关更多信息,请参阅此 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');
    } 
} 

用户.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

【讨论】:

  • 我试过这个包,它可以工作谢谢你,无论如何我宁愿等待下一个版本而不是安装更多的包
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-13
  • 2014-10-27
  • 2021-07-19
  • 2019-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多