Laravel-来自不同数据库的关系

时间:2018-12-04 06:31:51

标签: php laravel eloquent

我试图在联接表上应用where条件,但是出现此错误:

  

SQLSTATE [42S02]:找不到基表或视图:1146表'cts.plant'不存在(SQL:从tbl_complaint中选择*存在(从tbl_plant中选择*其中{ {1}}。tbl_complaint = made_in_planttbl_plantplant_id = 99999)按sap_code desc限制50偏移量0)排序

我的模型类如下所示:

主要型号

created

连接模型

    class Complaint extends Model {
        protected $connection= 'first';
        protected $table = 'complaint';
        protected $primaryKey = 'complaint_id';

    public function  customerPlant() {
        return $this->hasOne(Plant::class, 'plant_id', 'customer_plant_id')
                    ->select('plant_id', 'sap_code', 'plant_name');
    }
}

数据检索:

class Plant extends Model {
    protected $connection= 'second';
    protected $table = 'plant';
    protected $primaryKey = 'plant_id';

    public function getKeyName() {
        return 'plant_id';
    }
}

我认为问题是我没有指定连接的表在另一个数据库中。

1 个答案:

答案 0 :(得分:1)

如果表位于同一服务器上,但位于不同的数据库上,则可以执行此操作。

class Complaint extends Model {
    protected $table = 'cts.complaint';
    protected $primaryKey = 'complaint_id';

    public function  customerPlant(){
        return $this->hasOne(Plant::class, 'plant_id', 'customer_plant_id')
                ->select('plant_id', 'sap_code', 'plant_name');
    }
}

class Plant extends Model{
    protected $table = 'otherdatabase.plant';
    protected $primaryKey = 'plant_id';

    public function getKeyName() {
        return 'plant_id';
    }
}