关联模型
返回默认模型
这个特别重要!!!能避免关联数据不存在时导致的致命错误。
比如,我们可以在 belongsTo 关系中设置返回一个默认的模型,从而避免类似于使用
{
{ $post->user->name }}
当 $post->user 不存在的时候,引起的致命的错误。
在 Eloquent 关系中使用 OrderBy
可以在关联关系中直接指定 orderBy ()
比如设置关联关系的制售,指定根据name字段排序
public function products()
return $this->hasMany(Product::class);
public function productsByName()
return $this->hasMany(Product::class)->orderBy('name');
}
在 Eloquent 关系中添加条件
如果我们经常在模型关联关系中添加某些相同的 where 条件,可以抽取成一个独立方法。
指定和评论关联关系的同时,设置了approved=1,外部在调用的时候就可以直接调用这个方法了。
//指定和评论的关联关系
public function comments()
return $this->hasMany(Comment::class);
//指定和评论关联关系的同时,设置了approved=1,外部在调用的时候就可以直接调用这个方法了。
public function approved_comments()
return $this->hasMany(Comment::class)->where('approved', 1);
}
DB 原生查询: havingRaw ()
我们可以在很多地方使用原始数据库查询,比如在 groupBy() 后面调用 havingRaw()
Goods::groupBy('category_id')->havingRaw('COUNT(*) > 1')->get();
Eloquent 使用 has () 实现多层调用查询
我们可以在关联关系查询中使用 has() 实现两层关联查询。
// Teacher -> hasMany(Class::class);
// Class -> hasMany(Student::class);
$teachers = Teacher::has('classes.students')->get();
一对多关系中获取符合指定数量的数据
在一对多关系中,我们可以通过条件过滤,获取符合的数据。
比如需要查找有哪些老师负责的班级数量大于 5。
// Teacher -> hasMany(Class::class)
$teachers = Teacher::has('classes', '>', 5)->get();
一对多关系中一次创建多条关联数据
在一对多关系中,我们可以使用 saveMany() 通过一次提交,保存多条关联数据。
$article = Article::find(1);
$article->comments()->saveMany([ new Comment(['message' => 'First comment']),
new Comment(['message' => 'Second comment']),
]);
多层级渴求式加载
在 Laravel 中,我们可以在一条语句中渴求式加载多个层级。
$users = App\Book::with('author.country')->get();
渴求式加载特定字段
我们可以在 Laravel 中渴求式加载并指定关联中的特定字段。
$users = App\Book::with('author:id,name')->get();
我们还可以在深层级中这样做,如第二层级关系:
$users = App\Book::with('author.country:id,name')->get();