【154.1】laravel 查询构造器

分块结果

如果你需要处理上千条数据库记录,你可以考虑使用 chunk 方法。该方法一次获取结果集的一小块,并将其传递给 闭包 函数进行处理。该方法在 Artisan 命令 编写数千条处理数据的时候非常有用。例如,我们可以将全部 users 表数据切割成一次处理 100 条记录的一小块:

DB::table('users')->orderBy('id')->chunk(100, function ($users) {
    foreach ($users as $user) {
        //
    }
});

你可以通过在 闭包 中返回 false 来终止继续获取分块结果:

DB::table('users')->orderBy('id')->chunk(100, function ($users) {
    // Process the records...

    return false;
});

如果要在分块结果时更新数据库记录,则块结果可能会和预计的返回结果不一致。 因此,在分块更新记录时,最好使用 chunkById 方法。 此方法将根据记录的主键自动对结果进行分页:

DB::table('users')->where('active', false)
    ->chunkById(100, function ($users) {
        foreach ($users as $user) {
            DB::table('users')
                ->where('id', $user->id)
                ->update(['active' => true]);
        }
    });

参数分组

有时候你需要创建更高级的 where 子句,例如「where exists」或者嵌套的参数分组。 Laravel 的查询构造器也能够处理这些。下面,让我们看一个在括号中进行分组约束的例子:

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

laravel 的with 方法应用

 
应用场景:一对多的关联关系中。
作用:是为了避免N+1次的查询数据库, 从而提升查询的性能;
 
分类model
<?php
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Category extends Model
{
    /**
     * 分类下面的商品
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function goods()
    {
        return $this->hasMany(Good::class);
    }
}
 
 
商品model
<?php
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Good extends Model
{
    /**
     * 商品所属分类
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}
//查询某个分类下的商品方法
public function goods($categoryId)
{
     $category = Category::find($categoryId);
     $goods    = $category->goods;
     return $goods;
}
 
 
从同一个接口返回分类和属于该分类的商品,此刻就用到了with
public function category($categoryId)
{
    $category = Category::with('goods')->find($categoryId);
    return $category;
}
 
 
查询一个分类下已经上架的商品,用到了with另一方法
public function category($categoryId)
{
    $category = Category::with(['goods'=>function($query){
    	  $query->where('is_sale', 1);
	}])->find($categoryId);
    return $category;
}
 

laravel 的with的无限分类的用法

<?php

namespace App\Models\POI;

use App\Models\BaseModel;

class DataMapDistrictDictionary extends BaseModel
{
    /**
     * 旧数据库中采集的数据的表,
     * @Author: Mak
     * @DateTime: 2022/07/12
     *
     */
    protected $connection = '';
    protected $table = "表名";
    protected $primaryKey = 'id';
    protected $guarded = [];

    // 模型文件
    public function children() {
        return $this->hasMany(get_class($this), 'p_district_no' ,'district_no');
    }

    public function allChildren() {
        return $this->children()->with( 'allChildren' );
    }

// 获取父类 的模型信息
    public function  parent () {
        return $this->belongsTo(DataMapDistrictDictionary::class, 'p_district_no', 'district_no');
    }
    // 这个方法调用的时候 必须要用  with('getParent1') 这样的方法取,相当于取了模型对象的一个getParent1 的一个属性,这个属性存的是一个对象的值。
    public function getParent1() {
        return $this->parent()->with( 'getParent1' );
    }

}

hasOne 的用法

model 模型中写

 public function detail(){
        return $this->hasOne(PersonalCenterUserDetail::class, 'uid' ,'id');
    }

调用的时候写

$userRes = PersonalCenterUser::where('id',$uid)->with('detail')->get()->toArray();

这样就能返回结果
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值