我似乎无法弄清楚如何让一个数据库中的表与另一个数据库中的另一个表有关系。
像客户一样使用'目录'数据库。namespace App\Models;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Customer extends Model
{
use SoftDeletes;
protected $connection = 'directory';
public $fillable = [
'id',
'customer_type_id',
'user_id'
];
public function owners(){
return $this->hasMany(User::class)->whereHas('roles', function($query){ $query->where('name', 'owner');});
}
public function employees(){
return $this->hasMany(User::class)->whereHas('roles', function($query){ $query->where('name', 'employee');});
}
}
然后在User :: class中使用默认的'mysql'数据库
namespace App;
use App\Models\Customer_form;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, Notifiable, SoftDeletes;
protected $connection = 'mysql';
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected static function boot() {
// create an event to happen on deleting
static::deleting(function($user) {
$user->roles()->detach();
});
}
public function roles()
{
return $this
->belongsToMany("App\Role")
->withPivot('id','can_read', 'can_create', 'can_update', 'can_delete');
}
public function customer(){
return $this->belongsTo(App\Models\Customer::class, "customer_id", "id")->with("primaryName");
}
}
然后我在控制器中调用这种关系,如下:
$customerUsers = Customer::has('owners')->with('owners')->with('employees')->get();
然后它给我一个错误,就像它试图查询其中一个数据库,寻找一个在THAT数据库中不存在的表(“目录”)
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'directory.role_user' doesn't exist (SQL: select * from `customers` where exists (select * from `users` where `customers`.`id` = `users`.`customer_id` and exists (select * from `roles` inner join `role_user` on `roles`.`id` = `role_user`.`role_id` where `users`.`id` = `role_user`.`user_id` and `name` = owner)) and `customers`.`deleted_at` is null)
知道我错过了什么吗?或者你不能做跨数据库关系吗?
答案 0 :(得分:0)
选中此程序包,它使您可以使用跨数据库子查询(具有,wherehas,nottHave,whereDoesntHave,withCount)。
答案 1 :(得分:0)
我的问题的解决方案是在模型中使用属性方法来调用第二个数据库。