laravel CURD 笔记

这里我们用到了DB门面所以需要在控制器引入DB类 代码如下

use Illuminate\Support\Facades\DB;

DB门面为每种查询提供了相应方法 select() ,delete() , update() , insert() ,get() 等;
下面写一个简单查询

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * @return Response
     */
    public function index()
    {
        $users = DB::select('select * from users where active = ?', [1]); //按条件查询

        return view('user.index', ['users' => $users]); //调取页面,返回数据
    

}
}

原生查询没什么可说的,下面直接进入查询构造器
从一张表中取出所有行

我们可以从DB门面的table方法开始,table方法为给定表返回一个流式查询构建器实例,该实例允许你在查询上链接多个多约束条件并最终返回查询结果。在本例中,我们使用get方法获取表中所有记录:

<?php

namespace App\Http\Controllers;
 
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class UserController extends Controller{
    /**
     * 显示用户列表
     *
     * @return Response
     */
    public function index()
    {
        $users = DB::table('users')->get();

        return view('user.index', ['users' => $users]);
    }
}

从一张表中获取一行/一列

如果你只是想要从数据表中获取一行数据,可以使用first方法,该方法将会返回单个StdClass对象:

$user = DB::table('users')->where('name', 'John')->first();
echo $user->name;

如果你不需要完整的一行,可以使用value方法从结果中获取单个值,该方法会直接返回指定列的值:

$email = DB::table('users')->where('name', 'John')->value('email');

指定查询子句

当然,我们并不总是想要获取数据表的所有列,使用select方法,你可以为查询指定自定义的select子句:

$users = DB::table('users')->select('name', 'email as user_email')->get();
distinct方法允许你强制查询返回不重复的结果集:

$users = DB::table('users')->distinct()->get();

如果你已经有了一个查询构建器实例并且希望添加一个查询列到已存在的select子句,可以使用addSelect方法:

$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();

内连接(等值连接)

查询构建器还可以用于编写基本的SQL“内连接”,你可以使用查询构建器实例上的join方法,传递给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();

左连接

如果你是想要执行“左连接”而不是“内连接”,可以使用leftJoin方法。该方法和join方法的用法一样:

$users = DB::table('users')
            ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();

交叉连接

要执行“交叉连接”可以使用crossJoin方法,传递你想要交叉连接的表名到该方法即可。交叉连接在第一张表和被连接表之间生成一个笛卡尔积:

$users = DB::table('sizes')
            ->crossJoin('colours')
            ->get();

高级连接语句

你还可以指定更多的高级连接子句,传递一个闭包到join方法作为该方法的第二个参数,该闭包将会返回允许你指定join子句约束的JoinClause对象:

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

如果你想要在连接中使用“where”风格的子句,可以在查询中使用where和orWhere方法。这些方法将会将列和值进行比较而不是列和列进行比较:

DB::table('users')
        ->join('contacts', function ($join) {
            $join->on('users.id', '=', 'contacts.user_id')
                 ->where('contacts.user_id', '>', 5);
        })
        ->get();

简单where子句
使用查询构建器上的where方法可以添加where子句到查询中,调用where最基本的方法需要传递三个参数,第一个参数是列名,第二个参数是任意一个数据库系统支持的操作符,第三个参数是该列要比较的值。

例如,下面是一个验证“votes”列的值是否等于100的查询:

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

为了方便,如果你只是简单比较列值和给定数值是否相等,可以将数值直接作为where方法的第二个参数:

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

当然,你还可以使用其它操作符来编写where子句:

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

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

$users = DB::table('users')
            ->where('name', 'like', 'T%')
            ->get();

还可以传递条件数组到where函数:

$users = DB::table('users')->where([
    ['status', '=', '1'],
    ['subscribed', '<>', '1'],
])->get();

排序、分组、限定
orderBy

orderBy方法允许你通过给定字段对结果集进行排序,orderBy的第一个参数应该是你希望排序的字段,第二个参数控制着排序的方向——asc或desc:

$users = DB::table('users')
                ->orderBy('name', 'desc')
                ->get();
inRandomOrder

inRandomOrder方法可用于对查询结果集进行随机排序,比如,你可以用该方法获取一个随机用户:

$randomUser = DB::table('users')
                ->inRandomOrder()
                ->first();

groupBy / having / havingRaw

groupBy和having方法用于对结果集进行分组,having方法和where方法的用法类似:

$users = DB::table('users')
                ->groupBy('account_id')
                ->having('account_id', '>', 100)
                ->get();

havingRaw方法可用于设置原生字符串作为having子句的值,例如,我们可以这样找到所有售价大于$2500的部分:

$users = DB::table('orders')
                ->select('department', DB::raw('SUM(price) as total_sales'))
                ->groupBy('department')
                ->havingRaw('SUM(price) > 2500')
                ->get();

skip / take

想要限定查询返回的结果集的数目,或者在查询中跳过给定数目的结果,可以使用skip和take方法:

$users = DB::table('users')->skip(10)->take(5)->get();
作为替代方法,还可以使用limit和offset方法:

$users = DB::table('users')
                ->offset(10)
                ->limit(5)
                ->get();

删除(Delete)
当然,查询构建器还可以通过delete方法从表中删除记录:

DB::table('users')->delete();
DB::table('users')->where('votes', '>', 100)->delete();

如果你希望清除整张表,也就是删除所有列并将自增ID置为0,可以使用truncate方法:

DB::table('users')->truncate();

更新(Update)
当然,除了插入记录到数据库,查询构建器还可以通过使用update方法更新已有记录。update方法和insert方法一样,接收字段名和字段值的键值对数组包含要更新的列,你可以通过where子句来对update查询进行约束:

DB::table('users')
            ->where('id', 1)
            ->update(['votes' => 1]);

插入(Insert)
查询构建器还提供了insert方法用于插入记录到数据表。insert方法接收数组形式的字段名和字段值进行插入操作:

DB::table('users')->insert(
    ['email' => '[email protected]', 'votes' => 0]
);

你甚至可以一次性通过传入多个数组来插入多条记录,每个数组代表要插入数据表的记录:

DB::table('users')->insert([
    ['email' => '[email protected]', 'votes' => 0],
    ['email' => '[email protected]', 'votes' => 0]
]);

使用查询构造器中的聚合函数

count()
max()
min()
avg()
sum()
// $num = DB::table('student')->count();

// $max = DB::table('student')->max('age');

// $min = DB::table('student')->min('age');

// $avg = DB::table('student')->avg('age');

$sum = DB::table('student')->sum('age');

var_dump($sum);

猜你喜欢

转载自blog.csdn.net/weixin_44535476/article/details/89074175