为什么设置连接在嵌套关系中不起作用?
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'
];
}
自2018年以来,这是laravel的一个已知问题,有关更多信息,请参见此线程,此外还有一个开放拉取请求来解决此问题,该问题将在下一版本中得到解决。
现在您可以使用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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句