Home > PHP Framework > Laravel > body text

Eloquent ORM related operations in Laravel

藏色散人
Release: 2019-11-14 14:40:59
forward
3008 people have browsed it

定义

操作

获取(查询)

获取集合,(查询列表)

返回值是 IlluminateDatabaseEloquentCollection 的一个实例

获取所有的数据

use App\User;
$users = User::all();
Copy after login

条件获取列表

$users = User::where('active', 1)
             ->orderBy('name', 'desc')
             ->take(10)
             ->get();
Copy after login

获取数据列值

$result = User::where('gender', '1')->pluck('name');
 // 返回 ['name1','name2 ']
// 该自定义键必须是该表的其它字段列名,否则会报错
$result = User::where('gender', '1')->pluck('email','name');
// 返回 {"name1":"ed9@qq.com","name2":"ed89@qq.com"}
Copy after login

获取单个模型,(查询单条数据)

// 通过主键获取模型
$user = User::find(1);
// 获取匹配查询条件的第一个模型...
$user = User::where('active', 1)->first();
//  返回第一个gender为1的用户的名字
$name = User::where('gender', '1')->value('name');
// 传递主键数组来调用 find 方法,这将会返回匹配记录集合:
$users = App\Flight::find([1, 2, 3]);
如果没有任何查询结果,IlluminateDatabaseEloquentModelNotFoundException 异常将会被抛出:
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
Copy after login

处理结果集

$result = User::where('gender', '1')->chunk(5, function($users) {
            foreach ($users as $user) {
                $name = $user->name;
                echo $name;
            }
}) // 输出名字
// result 为 boolean  
$result = User::where('gender', '1')->chunk(5, function($users) {
            foreach ($users as $user) {
              $name = $user->name;
              if ($name == "dxx5") {
                 echo $name;
                 return false;
              }
           }
}) // 找出某个名字
Copy after login

聚合方法

// 获取总数
$count = Flight::where('active', 1)->count();
// 获取最大值
$max = Flight::where('active', 1)->max('price');
//平均值
$max = Flight::where('active', 1)->avg('price');
Copy after login

条件查询

select查询

  // 查询名字和email
    $users = User::select('name','email as user_email')->get();
    // 返回 [{"name":"name1","user_email":"1@qq.com"}]
    // 查询构建器实例,添加一个查询列到已存在的 select 子句
    $user = User::select('name');
    $users = $user->addSelect('gender')->get();
Copy after login

联合

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

注:unionAll 方法也是有效的,并且和 union 有同样的使用方式

Where子句

$users = User::where('gender', '=', 1)->get(); // 男性用户
$users = User::where('gender', 1)->get(); // 同上
$users = User::where('age', '>=', 10)->get(); // 10岁以上用户
$users = User::where(&#39;age&#39;, &#39;<>&#39;, 10)->get(); // 非10岁用户
$users = User::where(&#39;name&#39;, &#39;like&#39;, &#39;d%&#39;)->get(); // 名字为d开头的用户
$users = User::where(&#39;name&#39;, &#39;like&#39;, &#39;%d%&#39;)->get(); // 名字含d的用户
// 传递条件数组到 where 函数:
$users = User::where([[&#39;gender&#39;, &#39;=&#39;, &#39;1&#39;],[&#39;age&#39;, &#39;>&#39;, &#39;10&#39;]])->get(); //10岁以上的男孩
// or语句
$users = User::where(&#39;gender&#39;, &#39;=&#39;, 1)->orWhere(&#39;age&#39;, &#39;>&#39;, &#39;10&#39;)->get();
Copy after login

其他where语句

// whereBetween 方法验证列值是否在给定值之间:
$users = User::whereBetween(&#39;age&#39;, [1, 7])->get(); // 1-7岁的用户
// whereNotBetween 方法验证列值不在给定值之间:
$users = User::whereNotBetween(&#39;age&#39;, [1, 7])->get(); // 1-7岁以外的用户
// whereIn 方法验证给定列的值是否在给定数组中:
$users = User::whereIn(&#39;id&#39;, [1, 2, 3])->get();
// whereNotIn 方法验证给定列的值不在给定数组中:
$users = User::whereNotIn(&#39;id&#39;, [1, 2, 3])->get();
// whereNull 方法验证给定列的值为NULL:
$users = User::whereNull(&#39;updated_at&#39;)->get();
// whereNotNull 方法验证给定列的值不是 NULL:
$users = User::whereNotNull(&#39;updated_at&#39;)->get();
// whereDate 方法用于比较字段值和日期:
$users = User::whereDate(&#39;created_at&#39;, &#39;2018-05-10&#39;)->get(); // 20180510注册的用户
// whereMonth 方法用于比较字段值和一年中的指定月份:
$users = User::whereMonth(&#39;created_at&#39;, &#39;10&#39;)->get();
// whereDay 方法用于比较字段值和一月中的制定天:
$users = User::whereDay(&#39;created_at&#39;, &#39;10&#39;)->get();
whereYear 方法用于比较字段值和指定年:
$users = User::whereYear(&#39;created_at&#39;, &#39;2016&#39;)->get();
// whereColumn 方法用于验证两个字段是否相等,也可以传递一个比较运算符到该方法:
$users = User::whereColumn(&#39;first_name&#39;, &#39;last_name&#39;)->get();
$users = User::whereColumn(&#39;updated_at&#39;, &#39;>&#39;, &#39;created_at&#39;)->get();
        
// 还可以传递多条件数组到 whereColumn 方法,这些条件通过 and 操作符进行连接:
$users = User::whereColumn([
                [&#39;first_name&#39;, &#39;=&#39;, &#39;last_name&#39;],
                [&#39;updated_at&#39;, &#39;>&#39;, &#39;created_at&#39;]
            ])->get();
Copy after login

参数分组

$users = User::where(&#39;name&#39;, &#39;=&#39;, &#39;xxx&#39;)
        ->orWhere(function ($query) {
           $query->where(&#39;age&#39;, &#39;>&#39;, 5)
                 ->where(&#39;gender&#39;, 1);
        })
        ->get(); // xxx或大于5岁的男孩
where exit
$users = User::whereExists(function ($query) {
                $query->select(DB::raw(1))
                      ->from(&#39;articles&#39;)
                      ->whereRaw(&#39;articles.user_id = users.id&#39;);
})->get(); // 写过文章的用户
Copy after login

排序

$users = User::orderBy(&#39;age&#39;, &#39;desc&#39;)->get(); // 年龄倒序
$user = User::latest()->first(); //crate_at  最晚的那个
$user = User::oldest()->first(); //crate_at  最早的那个
$users = User::inRandomOrder()->first(); // 随机用户
Copy after login

限定

$users = User::skip(2)->take(3)->get(); // 跳过前2个取中间3个
$users = User::offset(2)->limit(3)->get(); // 同上
Copy after login

分组

$users = User::groupBy(&#39;name&#39;)->having(&#39;age&#39;, &#39;>&#39;, 10)->get(); // 大于10的用户
// 找到所有售价大于 $2,500 的部分, 没理解
$users = User::select(&#39;department&#39;, DB::raw(&#39;SUM(price) as total_sales&#39;))
    ->groupBy(&#39;department&#39;)
    ->havingRaw(&#39;SUM(price) > 2500&#39;)
    ->get();
when 条件子句
$sortBy = null; // 当sortBy为null,默认name排序
$users = User::when($sortBy, 
            function ($query) use ($sortBy) {
                return $query->orderBy($sortBy);
            }, function ($query) {
                return $query->orderBy(&#39;name&#39;);
            })
            ->get();
Copy after login

分页

$users = User::paginate(3);
$users->appends([&#39;sort&#39; => &#39;name&#39;])->links(); // 修改的是连接
$users->withPath(&#39;custom/url&#39;);
// 约束条件
$users = User::where(&#39;id&#39;, &#39;>&#39;, 2)->paginate(2);
$users = User::where(&#39;id&#39;, &#39;>&#39;, 2)->simplePaginate(2);
return $users->toArray();
Copy after login

返回结果:

当调用 paginate 方法时,你将获取IlluminatePaginationLengthAwarePaginator 实例,

调用方法simplePaginate 时,将会获取 IlluminatePaginationPaginator 实例。(不需要知道结果集中数据项的总数)

{
    "current_page" : 1
    "data": [{"id":1,"name":"name1"},{"id":2,"name":"name2"}]
    "from":1
    "last_page":2
    "next_page_url":"http://localhost:8888/user/page?page=2"
    "path":"http://localhost:8888/user/page"
    "per_page":3
    "prev_page_url":null
    "to":3
    "total":6
}
Copy after login

每个分页器实例都可以通过以下方法提供更多分页信息:

$results->count()
$results->currentPage()
$results->firstItem()
$results->hasMorePages()
$results->lastItem()
$results->lastPage() (使用simplePaginate 时无效)
$results->nextPageUrl()
$results->perPage()
$results->previousPageUrl()
$results->total() (使用simplePaginate 时无效)
$results->url($page)
Copy after login

插入

插入

$user = new User;
$user->name = "username";
$user->fill([&#39;grade&#39; => &#39;2&#39;]); // 使用 fill 方法通过数组属性来填充
$user->save();
$row = array(&#39;name&#39; => str_random(3),&#39;email&#39; => str_random(3).&#39;@qq.com&#39;)
$user = User::create($row); // 返回模型对象
$id = User::insertGetId($row); // 插入记录并返回ID值
$success = User::nsert([
    [&#39;email&#39; => &#39;taylor@example.com&#39;, &#39;votes&#39; => 0],
    [&#39;email&#39; => &#39;dayle@example.com&#39;, &#39;votes&#39; => 0]
]); // 插入多条
Copy after login

更新

单个更新

$user = User::find(1);
$user->name = &#39;new name&#39;;
$user->save();
Copy after login

批量更新

User::where(&#39;gender&#39;, 1)->update([&#39;age&#39; => 1]);
Copy after login

自增自减

$result = User::increment(&#39;age&#39;); // 返回修改的行数
$result = User::increment(&#39;age&#39;, 2);
$result = User::decrement(&#39;age&#39;);
$result = User::decrement(&#39;age&#39;, 2);
$result = User::increment(&#39;age&#39;,1,[&#39;gender&#39; => 1]); // 年龄自增1 且 性别改为1
Copy after login

其他创建方法

$user = User::firstOrCreate([&#39;name&#39; => &#39;Flight 10&#39;]); // 不存在则创建
$user = User::firstOrNew([&#39;name&#39; => &#39;Flight 10&#39;]); // 如果不存在初始化一个新的实$user = User::updateOrCreate(
    [&#39;name&#39; => &#39;username&#39;, &#39;age&#39; => &#39;16&#39;],
    [&#39;grade&#39; => 3]
); // 将 16岁的username 改成3年级,没有则创建
Copy after login

删除

$user = User::find(1);
$user->delete(); // 通过主键查询后,删除模型
User::destroy(1); // 直接通过主键删除
User::destroy([1, 2, 3]);
User::destroy(1, 2, 3);
$deletedRows = User::where(&#39;age&#39;, 0)->delete(); //查询 删除
// 注:通过 Eloquent 批量删除时,deleting 和 deleted 事件不会被触发,因为在进行模型删除时不会获取模型。
Copy after login

软删除

当模型被软删除后,它们并没有真的从数据库删除,而是在模型上设置一个 deleted_at 属性并插入数据库,如果模型有一个非空 deleted_at 值,那么该模型已经被软删除了。

启用模型的软删除功能,可以使用模型上的IlluminateDatabaseEloquentSoftDeletes trait并添加 deleted_at 列到 $dates 属性:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Flight extends Model
{
    use SoftDeletes;
    // 应该被调整为日期的属性,并添加 deleted_at 列到数据表
    protected $dates = [&#39;deleted_at&#39;];
}
// Laravel Schema 构建器包含一个辅助函数来创建该数据列:
Schema::table(&#39;flights&#39;, function ($table) {
    $table->softDeletes();
});
Copy after login

现在,当调用模型的 delete 方法时,deleted_at 列将被设置为当前日期和时间.

当查询一个使用软删除的模型时,被软删除的模型将会自动从查询结果中排除。

软删除的查询

判断给定模型实例是否被软删除,可以使用 trashed 方法:

if ($flight->trashed()) {
    //
}
// 如果你想要软删除模型出现在查询结果中,可以使用 withTrashed 方法:
$flights = App\Flight::withTrashed()
            ->where(&#39;account_id&#39;, 1)
            ->get();
            
// withTrashed 方法也可以用于关联查询中:
$flight->history()->withTrashed()->get();
// onlyTrashed 方法只获取软删除模型:
$flights = App\Flight::onlyTrashed()
            ->where(&#39;airline_id&#39;, 1)
            ->get();
            
// 恢复软删除模型,使用restore 方法:
$flight->restore();
// 快速恢复多个模型,同样,这也不会触发任何模型事件:
App\Flight::withTrashed()
    ->where(&#39;airline_id&#39;, 1)
    ->restore();
    
// 也可以用于关联查询:
$flight->history()->restore();
// 永久删除模型,可以使用 forceDelete 方法:
$flight->forceDelete(); // 强制删除单个模型实例...
$flight->history()->forceDelete(); // 强制删除所有关联模型...
Copy after login

The above is the detailed content of Eloquent ORM related operations in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template