$post = Post::with(['comments' => function ($query) { $query->where('content', 'like', 'Laravel学院%') ->orderBy('created_at', 'desc'); }])->where('id', '<', 5)->get(); 底层执行的 SQL 语句如下: 代码语言:javascript 代码运行次数:0 运行 AI代码解释 select * from `posts...
$roles = App\User::find(1)->roles()->orderBy('name')->get(); 正如前面所提到的,为了确定关联关系连接表的表名,Eloquent 以字母顺序连接两个关联模型的名字。不过,你可以重写这种约定 —— 通过传递第二个参数到 belongsToMany 方法:return $this->belongsToMany('App\Role', 'user_roles'); 除了...
$users = App\User::with(['posts' => function ($query) { $query->orderBy('created_at', 'desc'); }])->get();Copy延遲預載入有時你可能需要在上層模型已經被取得後才預載入關聯。例如,當你需要動態決定是否載入關聯模型時相當有幫助:$books = App\Book::all(); if ($someCondition) { $...
$query->where('title', 'like', '%first%'); }])->get(); 在这个例子中,Eloquent会值预加载文章的title列包含first单词的记录。当然,你也可以调用其他查询生成器可用的方法: $users = App\User::with(['posts' => function ($query) { $query->orderBy('created_at', 'desc'); }])->get();...
Model::with('relation')->get(); Model::all()->take(10); Model::all()->skip(10); // 默认的 Eloquent 排序是上升排序 Model::all()->orderBy('column'); Model::all()->orderBy('column','desc'); 软删除 Model::withTrashed()->where('cars', 2)->get(); // 在查询结果中包括带...
class TournamentsController extends Controller public function whatever_method() { $tournaments = Tournament::with(['countries' => function($query) { $query->orderBy('position'); }])->latest()->get(); }whereHas 的一个更简短的方法在Laravel 8.57 中发布:通过包含一个简单条件的简短方法来写 ...
$users = App\User::with(['posts' => function ($query) { $query->orderBy('created_at', 'desc'); }])->get();延迟预加载有时你可能需要在上层模型被获取后才预加载关联。当你需要来动态决定是否加载关联模型时会很有帮助,如下所示:$books = App\Book::all(); if ($someCondition) { $...
你可以组合使用 using 和withPivot 从中间表来检索列。例如,通过将列名传递给 withPivot 方法,就可以从 UserRole 中间表中检索出 created_by 和updated_by 两列数据:<?php namespace App; use Illuminate\Database\Eloquent\Model; class Role extends Model { /** * 拥有此角色的用户 */ public function ...
在 Eloquent 模型上进行关联查询主要分为两种方式,一种是懒惰式加载(动态属性),一种是渴求式加载(通过with方法)。从性能上来说,渴求式加载更优,因为它会提前从数据库一次性查询所有关联数据,而懒惰式加载在每次查询动态属性的时候才会去执行查询,会多次连接数据库,性能上差一些(数据库操作主要开销在数据库连接上,...
$users = App\User::with(['posts' => function ($query) { $query->orderBy('created_at', 'desc');}])->get();延迟预加载有时,您可能需要在获得父级模型后才去预加载关联数据。例如,当你需要来动态决定是否加载关联模型时,这可能很有帮助:...