Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vignesh.svn's avatar

How to compare two tables and insert the match data in another table

I have two tables one is "table1" which contains column (user_id, name, address, pincode, address, jobrole, usertype,recordno) and "table2" which contains (name,address,pincode). i want to find all the records that matches in table2. Table1 data will very frequently and table2 is permanent. so i want to find all the data's that match in table2.

0 likes
6 replies
tisuchi's avatar

In order to join two tables, you need a foreign key in second table. I am considering pincode is the foreign key.

In this case, we can do that in few ways.

  • Relationships
  • Join Tables

Relationships

In table1 model.

public function table2()
    {
        return $this->hasOne('App\Table2', 'pincode');
    }

In table2 model.

public function table1()
    {
        return $this->belongsTo('App\Table1', 'pincode');
    }

Now you can access based on relationships. Ref: https://laravel.com/docs/5.4/eloquent-relationships#one-to-one

Join Tables

In this case, you can join two tables-

DB::table('table1')
            ->join('table2', 'table1.pincode', '=', 'table2.pincode')
            ->select('table1.*', 'table2.*')
            ->get();

Ref: https://laravel.com/docs/5.4/queries#joins

1 like
vignesh.svn's avatar

In the table2 also have "id" in the table and then how can i compare match data and then insert the match data in another table called "table3"

tisuchi's avatar

Than simply just follow this concept-

$users = DB::table('users')
            ->join('contacts', 'users.id', '=', 'contacts.user_id')
            ->join('orders', 'users.id', '=', 'orders.user_id')
            ->select('users.*', 'contacts.phone', 'orders.price')
            ->get();

Ref: https://laravel.com/docs/5.4/queries#joins

vignesh.svn's avatar

My question is compare the two tables and find the match data and then insert into another newtable.

Please or to participate in this conversation.