> PHP 프레임워크 > Laravel > Laravel의 Eloquent ORM 관련 작업

Laravel의 Eloquent ORM 관련 작업

藏色散人
풀어 주다: 2019-11-14 14:40:59
앞으로
3074명이 탐색했습니다.

定义

操作

获取(查询)

获取集合,(查询列表)

返回值是 IlluminateDatabaseEloquentCollection 的一个实例

获取所有的数据

use App\User;
$users = User::all();
로그인 후 복사

条件获取列表

$users = User::where('active', 1)
             ->orderBy('name', 'desc')
             ->take(10)
             ->get();
로그인 후 복사

获取数据列值

$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"}
로그인 후 복사

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

// 通过主键获取模型
$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();
로그인 후 복사

处理结果集

$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;
              }
           }
}) // 找出某个名字
로그인 후 복사

聚合方法

// 获取总数
$count = Flight::where('active', 1)->count();
// 获取最大值
$max = Flight::where('active', 1)->max('price');
//平均值
$max = Flight::where('active', 1)->avg('price');
로그인 후 복사

条件查询

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();
로그인 후 복사

联合

$first = DB::table('users')
            ->whereNull('first_name');
$users = DB::table('users')
            ->whereNull('last_name')
            ->union($first)
            ->get();
로그인 후 복사

注: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();
로그인 후 복사

其他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();
로그인 후 복사

参数分组

$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(); // 写过文章的用户
로그인 후 복사

排序

$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(); // 随机用户
로그인 후 복사

限定

$users = User::skip(2)->take(3)->get(); // 跳过前2个取中间3个
$users = User::offset(2)->limit(3)->get(); // 同上
로그인 후 복사

分组

$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();
로그인 후 복사

分页

$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();
로그인 후 복사

返回结果:

当调用 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
}
로그인 후 복사

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

$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)
로그인 후 복사

插入

插入

$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]
]); // 插入多条
로그인 후 복사

更新

单个更新

$user = User::find(1);
$user->name = &#39;new name&#39;;
$user->save();
로그인 후 복사

批量更新

User::where(&#39;gender&#39;, 1)->update([&#39;age&#39; => 1]);
로그인 후 복사

自增自减

$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
로그인 후 복사

其他创建方法

$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年级,没有则创建
로그인 후 복사

删除

$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 事件不会被触发,因为在进行模型删除时不会获取模型。
로그인 후 복사

软删除

当模型被软删除后,它们并没有真的从数据库删除,而是在模型上设置一个 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();
});
로그인 후 복사

现在,当调用模型的 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(); // 强制删除所有关联模型...
로그인 후 복사

위 내용은 Laravel의 Eloquent ORM 관련 작업의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:segmentfault.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿