简体   繁体   中英

How to combine two different tables in different database using SQL in laravel

Expect:

  1. select robotid, number from tool where is_active = 1
  2. select * from robot_team where id = robotid( robotid from tool)
  3. foreach id(from robot_team), number(from tool), status_za(from robot_team), status_zb(from robot_team), status_zm(from robot_team), status_qs(from robot_team)

Result:

  1. cannot show success through postman

Code:

public function robotStatus()
    {
        $arr=[];
                
        $robotlist = DB::table('robot_team AS u')
                ->Join(DB::connection('sql')->table('tool AS m'), 'u.id', '=', 'm.robotid')
                ->select('u.*', 'u.id AS uid', 'm.number AS mnumber')
                ->where('m.is_active', '=', 1)
                ->orderBy('u.id', 'desc')
                ->get();
        if(count($robotlist)>0){
        foreach ($robotlist as $v) {

            $robot_arr = [
            "id" => $v->uid,
            "number" => $v->mnumber,
            "FA" => $v->status_fa,
            "FC" => $v->status_fc,
            "FM" => $v->status_fm,
            "PS" => $v->status_ps
            ];
            $arr[]=$robot_arr;
        }}

        return $arr;


    }

Comment:

Hello all,

Laravel: join two tables of different db connections

I try to combine using the above code but it is fail.

I have read the above link but it cannot reach my purpose as two table in different db in mysql.

Please help me to solve the above problems.

Thank you all.

When using ->Join you are asking the database to join data tables before the result set hits your application code. For that to work regardless of programming language and framework the two databases must reside within the same database server. It is unclear from your question if that is the case here.

Even if the two databases reside on the same server I'm not sure that Laravel supports joins across different connections. The Laravel documentation doesn't mention it , but it might be supported anyway. Perhaps the actual error message (rather than "but it is fail") would shed some light on the problem.

If your data sets are fairly small I would recommend you to combine the data sets manually using PHP code. If your data sets are big I would explore the possibility to replicate data from the one database into the other database (to have access to both tables in the same database).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM