📌  相关文章
📜  laravel query select from table where id != to another table id - PHP Code Example(1)

📅  最后修改于: 2023-12-03 15:17:12.901000             🧑  作者: Mango

Laravel Query: Select from Table where ID is not equal to Another Table ID

In Laravel, you can use the Eloquent ORM to perform queries on your database tables. If you need to select records from one table where the ID is not equal to the ID in another table, you can achieve this by using the whereNotIn method with a subquery.

Assuming you have two tables named table1 and table2, with a common column id, the following example demonstrates how to select records from table1 where the ID is not equal to any ID in table2.

use Illuminate\Support\Facades\DB;

$table1Data = DB::table('table1')
    ->whereNotIn('id', function ($query) {
        $query->select('id')
            ->from('table2');
    })
    ->get();

In the above code, we use the whereNotIn method to specify the column id that should not be present in the subquery result. The subquery is created using the select method chained with from method to select the id column from table2.

By executing the above code, you will get a collection containing the records from table1 where the ID is not equal to any ID in table2.

Make sure to replace table1 and table2 with your actual table names in the code.

This query can be useful when you want to filter or exclude records based on the IDs present in another table.