laravel5.6 belongsTo和hasOne连接不同数据库的表

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tclzsn7456/article/details/86581359

首先

A hasOne B 表示 A.b_id = B.id
C belongsTo B 表示 C.id = B.c_id

举例:这里我们假定在B的模型里:

protected $table = '要连的表名A';

//protected $table = '要连的表名C';

public function getA()

{

//如果连不同库的表

        return $this->setConnection('config中database.php中的A表所在库的连接名')

->hasOne('\App\Components\控制器同名\Models\XXXX(要连表的模型名A)', 'id', 'b_id');

//如果连相同库的表

        return $this->hasOne('\App\Components\控制器同名\Models\XXXX(要连表的模型名A)', 'id', 'b_id');

}

public function getC()

{

//如果连不同库的表

        return $this->setConnection('config中database.php中的A表所在库的连接名')

->belongsTo('\App\Components\控制器同名\Models\XXXX(要连表的模型名C)', 'id', 'c_id');

//如果连相同库的表

        return $this->belongsTo('\App\Components\控制器同名\Models\XXXX(要连表的模型名C)', 'id', 'c_id');

}

猜你喜欢

转载自blog.csdn.net/tclzsn7456/article/details/86581359