📜  laravel 向关系添加条件 - PHP (1)

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

Laravel 向关系添加条件

在 Laravel 中,我们可以使用 where 方法向关系添加条件。

1. 基本用法
$users = DB::table('users')
                ->join('contacts', 'users.id', '=', 'contacts.user_id') // 表关联
                ->where('contacts.city', '=', '北京') // 添加条件
                ->get();

在上面的示例中,我们通过 join 方法关联了 userscontacts 表,并使用 where 方法添加了 contacts.city = '北京' 的条件。最终获取了满足条件的结果集。

2. 多个条件

我们可以通过多次调用 where 方法添加多个条件:

$users = DB::table('users')
                ->join('contacts', 'users.id', '=', 'contacts.user_id')
                ->where('contacts.city', '=', '北京')
                ->where('contacts.status', '=', 1) // 添加多个条件
                ->get();

在上面的示例中,我们添加了两个条件 contacts.city = '北京'contacts.status = 1

3. 比较运算符

where 方法中,我们可以使用比较运算符来添加条件。例如,可以使用 >>=<<==<> 等运算符:

$users = DB::table('users')
                ->join('contacts', 'users.id', '=', 'contacts.user_id')
                ->where('contacts.created_at', '>', '2022-01-01') // > 运算符
                ->where('contacts.status', '<>', 0) // <> 运算符
                ->get();

在上面的示例中,我们添加了两个条件 contacts.created_at > '2022-01-01'contacts.status <> 0

4. 原始表达式

如果需要使用一些更为复杂的条件,可以使用 whereRaw 方法添加原始表达式:

$users = DB::table('users')
                ->join('contacts', 'users.id', '=', 'contacts.user_id')
                ->whereRaw('contacts.created_at > ? and contacts.status <> ?', ['2022-01-01', 0]) // 原始表达式
                ->get();

在上面的示例中,我们添加了一个原始表达式 contacts.created_at > '2022-01-01' and contacts.status <> 0。注意,我们在第二个参数中传递了对应变量的值,以防止 SQL 注入攻击。

以上就是向关系添加条件的基本用法,希望对大家有所帮助。