• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

关于Laravel框架数据库CURD操作和连贯操作的解析

php 搞代码 3年前 (2022-01-22) 23次浏览 已收录 0个评论

这篇文章主要介绍了Laravel框架数据库CURD操作、连贯操作、链式操作总结,本文包含大量数据库操作常用方法,需要的朋友可以参考下

一、Selects

检索表中的所有行

$users = DB::table('users')->get();foreach ($users as $user){var_dump($user->name);}

从表检索单个行

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

检索单个列的行

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

检索一个列值列表

$roles = DB::table('roles')->lists('title');

该方法将返回一个数组标题的作用。你也可以指定一个自定义的键列返回的数组

$roles = DB::table('roles')->lists('title', 'name');

指定一个Select子句

$users = DB::table('users')->select('name', 'email')->get(); $users = DB::table('users')->distinct()->get(); $users = DB::table('users')->select('name as user_name')->get();

Select子句添加到一个现有的查询$query = DB::table('users')->select('name');

$users = $query->addSelect('age')->get();

where

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

OR

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

Where Between

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

Where Not Between

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

Where In With An Array

$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();$users = DB::table('users')->whereNotIn('id', array(1, 2, 3))->get();

Using Where Null To Find Records With Unset Values

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

Order By, Group By, And Having

$users = DB::table('users')->orderBy('name', 'desc')->groupBy('count')->having('count', '>', 100)->get();

Offset & Limit

$users = DB::table('users')->skip(10)->take(5)->get();

二、连接

Joins

查询构建器也可以用来编写连接语句。看看下面的例子:

Basic Join Statement

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

左连接语句

DB::table('users')  ->leftJoin('posts', 'users.id', '=', 'posts.user_id')  ->get();  DB::table('users')  ->join('contacts', function($join)  {  $join->on('<b>/本文来源gao@!dai!ma.com搞$$代^@码5网@</b><strong>搞代gaodaima码</strong>users.id', '=', 'contacts.user_id')->orOn(...);  })  ->get();  DB::table('users')  ->join('contacts', function($join)  {  $join->on('users.id', '=', 'contacts.user_id')  ->where('contacts.user_id', '>', 5);  })  ->get();

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:关于Laravel框架数据库CURD操作和连贯操作的解析

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址