编程

Laravel 编程技巧——数据库模型与 Eloquent(1)

919 2022-01-09 21:26:43

复用或克隆query

通常,我们需要从过滤后的查询中进行更多次查询。因此,大多数时候我们使用 query() 方法, 让我们编写一个查询来获取今天创建的可用和不可用的产品

$query = Product::query();


$today = request()->q_date ?? today();
if($today){
    $query->where('created_at', $today);
}

// 让我们获取可用和不可用的产品
$active_products = $query->where('status', 1)->get(); // 这一行 修改了$query 对象变量
$inactive_products = $query->where('status', 0)->get(); // 所以这里我们将获取不到任何不可用产品
但是,在获得 $active products 后,$query 会被修改。因此 $inactive_products 不会从 $query 中获取到不可用产品,并且每次都返回空集合。因为,它尝试从 $active_products 中查找不可用产品($query 仅返回可用产品)。

为了解决这个问题,我们可以通过重用这个$query对象来查询多次。因此我们在做任何对$query修改操作的时候需要克隆这个$query。

$active_products = (clone $query)->where('status', 1)->get(); // it will not modify the $query
$inactive_products = (clone $query)->where('status', 0)->get(); // so we will get inactive products from $query

Eloquent where日期方法

在 Eloquent 中,使用 whereDay()、whereMonth()、whereYear()、whereDate() 和 whereTime() 函数检查日期。

$products = Product::whereDate('created_at', '2018-01-31')->get();
$products = Product::whereMonth('created_at', '12')->get();
$products = Product::whereDay('created_at', '31')->get();
$products = Product::whereYear('created_at', date('Y'))->get();
$products = Product::whereTime('created_at', '=', '14:13:58')->get();

增量和减量

如果要增加数据库某个表中的某个列的值,只需要使用 increment() 函数。你不仅可以增加 1,还可以增加其他数字,如 50。

Post::find($post_id)->increment('view_count');
User::find($user_id)->increment('points', 50);

禁止 timestamp 列

如果你的数据库表不包含 timestamp 字段 created_at 和 updated_at,你可以使用 $timestamps = false 属性指定 Eloquent 模型不使用它们。

class Company extends Model
{
    public $timestamps = false;
}

软删除-多行恢复

使用软删除时,可以在一个句子中恢复多行。

Post::onlyTrashed()->where('author_id', 1)->restore();

Model all-columns

当调用Eloquent's Model::all()时你可以指定返回哪些列。

$users = User::all(['id', 'name', 'email']);

To Fail or not to Fail

除了 findOrFail() 之外,还有 Eloquent 方法 firstOrFail(),如果没有找到查询记录,它将返回 404 页面。

$user = User::where('email', 'povilas@laraveldaily.com')->firstOrFail();

列名修改

在 Eloquent Query Builder 中,您可以像在普通 SQL 查询中一样指定as以返回任何列的别名。

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