laravel数据库: 查询构造器

数据库: 查询构造器

获取结果

  1. 从表中检索所有行
  • get
use Illuminate\Support\Facades\DB;

$users = DB::table('users')->get();
//可以将列作为对象的属性来访问每列的值
foreach ($users as $user) {
    echo $user->name;
}
  1. 从表中检索单行或单列
  • first :检索单行
$user = DB::table('users')->where('name', 'John')->first();
return $user->email;
  • value :提取单个值
$email = DB::table('users')->where('name', 'John')->value('email');
  • find:通过 id 字段值获取单行数据
//()必填
$user = DB::table('users')->find(3);
  1. 获取某一列的值

pluck

  • 包含单列值的集合
$titles = DB::table('users')->pluck('title');

foreach ($titles as $title) {
    echo $title;
}
  • 第二个参数来指定结果集中要作为键的列
$titles = DB::table('users')->pluck('title', 'name');

foreach ($titles as $name => $title) {
    echo $title;
}

聚合

  1. count, max, min, avg
  2. 判断记录是否存在
DB::table('orders')->where('finalized', 1)->count()
DB::table('orders')->where('finalized', 1)->exists()
DB::table('orders')->where('finalized', 1)->doesntExist()

Select 说明

自定义一个 「select」 查询语句来查询指定的字段

  1. select
$users = DB::table('users')
            ->select('name', 'email as user_email')
            ->get();
  1. distinct
$users = DB::table('users')->distinct()->get();
  1. addSelect
$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();

原生表达式

  1. raw
$users = DB::table('users')
             ->select(DB::raw('count(*) as user_count, status'))
             ->where('status', '<>', 1)
             ->groupBy('status')
             ->get();
  1. selectRaw : 代替 addSelect(DB::raw(…))
$orders = DB::table('orders')
                ->selectRaw('price * ? as price_with_tax', [1.0825])
                ->get();
  1. whereRaw / orWhereRaw : 将原生的 「where」 注入到你的查询
$orders = DB::table('orders')
                ->whereRaw('price > IF(state = "TX", ?, 100)', [200])
                ->get();
  1. havingRaw / orHavingRaw : 将原生字符串作为 「having」 语句的值
$orders = DB::table('orders')
                ->select('department', DB::raw('SUM(price) as total_sales'))
                ->groupBy('department')
                ->havingRaw('SUM(price) > ?', [2500])
                ->get();
  1. orderByRaw : 将原生字符串设置为 「order by」 语句的值
$orders = DB::table('orders')
                ->orderByRaw('updated_at - created_at DESC')
                ->get();
  1. groupByRaw : 将原生字符串设置为 group by 语句的值
$orders = DB::table('orders')
                ->select('city', 'state')
                ->groupByRaw('city, state')
                ->get();

Joins

  1. Inner Join 语句
$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();
  1. Left Join / Right Join 语句
$users = DB::table('users')
            ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();

$users = DB::table('users')
            ->rightJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();
  1. Cross Join 语句
$sizes = DB::table('sizes')
            ->crossJoin('colors')
            ->get();
  1. 高级 Join 语句
  2. 子连接查询
$latestPosts = DB::table('posts')
                   ->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
                   ->where('is_published', true)
                   ->groupBy('user_id');

$users = DB::table('users')
        ->joinSub($latestPosts, 'latest_posts', function ($join) {
            $join->on('users.id', '=', 'latest_posts.user_id');
        })->get();

Unions

$first = DB::table('users')
            ->whereNull('first_name');

$users = DB::table('users')
            ->whereNull('last_name')
            ->union($first)
            ->get();

Where语句

条件查询语句

  1. =
where('votes', '=', 100)
where('votes', 100)
  1. 其他操作符
where('votes', '>=', 100)
where('votes', '<>', 100)
where('name', 'like', 'T%')
  1. 条件数组
where([
    ['status', '=', '1'],
    ['subscribed', '<>', '1'],
])

Or Where 语句

$users = DB::table('users')
                    ->where('votes', '>', 100)
                    ->orWhere('name', 'John')
                    ->get();

select * from users where votes > 100 or (name = ‘Abigail’ and votes > 50)

$users = DB::table('users')
            ->where('votes', '>', 100)
            ->orWhere(function($query) {
                $query->where('name', 'Abigail')
                      ->where('votes', '>', 50);
            })
            ->get();

Where Not 语句

“whereNot”和“orWhereNot”方法可用于否定给定的一组查询约束

    $products = DB::table('products')
                    ->whereNot(function ($query) {
                        $query->where('clearance', true)
                              ->orWhere('price', '<', 10);
                    })
                    ->get();

其他 Where 语句

  1. whereBetween / orWhereBetween / whereNotBetween / orWhereNotBetween
whereBetween('votes', [1, 100])
  1. whereIn / whereNotIn / orWhereIn / orWhereNotIn
whereIn('id', [1, 2, 3])
  1. whereNull / whereNotNull / orWhereNull / orWhereNotNull
whereNull('updated_at')
  1. whereDate / whereMonth / whereDay / whereYear / whereTime
whereDate('created_at', '2016-12-31')
whereMonth('created_at', '12')
whereDay('created_at', '31')
whereYear('created_at', '2016')
whereTime('created_at', '=', '11:20:45')
  1. whereColumn / orWhereColumn
whereColumn('first_name', 'last_name')
whereColumn('updated_at', '>', 'created_at')
whereColumn([
	['first_name', '=', 'last_name'],
	['updated_at', '>', 'created_at'],
])

逻辑分组

select * from users where name = ‘John’ and (votes > 100 or title = ‘Admin’)

$users = DB::table('users')
           ->where('name', '=', 'John')
           ->where(function ($query) {
               $query->where('votes', '>', 100)
                     ->orWhere('title', '=', 'Admin');
           })
           ->get();

高级 Where 语句

WhereExists语句

$users = DB::table('users')
           ->whereExists(function ($query) {
               $query->select(DB::raw(1))
                     ->from('orders')
                     ->whereColumn('orders.user_id', 'users.id');
           })
           ->get();
//select * from users
//where exists (
//    select 1
//    from orders
//    where orders.user_id = users.id
//)

子查询 Where 语句

//子查询的结果与给定的值进行比较
$users = User::where(function ($query) {
    $query->select('type')
        ->from('membership')
        ->whereColumn('membership.user_id', 'users.id')
        ->orderByDesc('membership.start_date')
        ->limit(1);
}, 'Pro')->get();
//构建一个“where”子句,将列与子查询的结果进行比较
$incomes = Income::where('amount', '<', function ($query) {
    $query->selectRaw('avg(i.amount)')->from('incomes as i');
})->get();

Ordering, Grouping, Limit & Offset

  1. orderBy 方法
//要按多列排序,您可以根据需要多次调用 orderBy
orderBy('name', 'desc')
  1. latest 和 oldest 方法 : 默认根据数据表的 created_at 字段进行排序
$user = DB::table('users')
                ->latest()
                ->first();
  1. 随机排序
$randomUser = DB::table('users')
                ->inRandomOrder()
                ->first();
  1. 移除已存在的排序
$query = DB::table('users')->orderBy('name');

$unorderedUsers = $query->reorder()->get();
//传递一个列名和排序方式去重新排序整个查询:
$usersOrderedByEmail = $query->reorder('email', 'desc')->get();

分组

groupBy 和 having 方法

groupBy('account_id')
groupBy('first_name', 'status')
having('account_id', '>', 100)
havingBetween('number_of_orders', [5, 15])

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Laravel 中,异常处理是非常重要的。Laravel 提供了一种方便的方式来捕获、处理和创建异常。 首先,让我们来看一下如何捕获异常。Laravel 中的异常处理器是通过 Exception 类来实现的。当 Laravel 应用程序中的异常被抛出时,这些异常将被传递给 Exception 类。我们可以通过在应用程序中注册异常处理器来处理这些异常。这可以通过在 app/Exceptions/Handler.php 文件中编写代码来完成。 下面是一个例子: ```php <?php namespace App\Exceptions; use Exception; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; class Handler extends ExceptionHandler { public function render($request, Exception $exception) { if ($exception instanceof CustomException) { return response()->view('errors.custom', [], 500); } return parent::render($request, $exception); } } ``` 在这个例子中,我们重写了 render 方法,并检查抛出的异常是否是 CustomException 类型。如果是,我们将返回一个自定义的错误视图,否则返回默认的错误视图。 接下来,让我们来看一下如何处理异常。在 Laravel 中,我们可以通过 try-catch 语句来处理异常。例如: ```php try { // Some code } catch (Exception $e) { // Handle exception } ``` 在这个例子中,我们将一些代码包装在 try 块中。如果在 try 块中抛出了异常,它将被捕获并传递给 catch 块。在 catch 块中,我们可以编写代码来处理异常。 最后,让我们看一下如何创建异常。在 Laravel 中,我们可以通过继承 Exception 类来创建自定义异常。例如: ```php <?php namespace App\Exceptions; use Exception; class CustomException extends Exception { public function __construct($message = "", $code = 0, Throwable $previous = null) { parent::__construct($message, $code, $previous); } } ``` 在这个例子中,我们创建了一个 CustomException 类,它继承自 Exception 类。我们还为该类定义了一个构造函数,它接受消息、代码和前一个异常作为参数。 总之,Laravel 中的异常处理非常重要。通过捕获、处理和创建异常,我们可以更好地管理我们的应用程序并提供更好的用户体验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值