publicfunctionbelongsToMany($related,$table=null,$foreignPivotKey=null,$relatedPivotKey=null,$parentKey=null,$relatedKey=null,$relation=null) 第一个参数是关联模型的类名。第二个参数是中间表,第三个参数是中间表中当前模型类的外键,第四个参数是中间表当前关联模型类的外键,第五个参数表示对应当前模型的哪...
如果要统计其它关联模型结果数量字段,可以依次类推,对应字段都是 {relation}_count 结构。 注:实际开发中为了提高查询性能,我们往往是在 posts 表中冗余提供一个 comments_count 字段,每新增一条评论,该字段值加 1,查询的时候直接取该字段即可,从而提高查询的性能。
如果要统计其它关联模型结果数量字段,可以依次类推,对应字段都是 {relation}_count 结构。注:实际开发中为了提高查询性能,我们往往是在 posts 表中冗余提供一个 comments_count 字段,每新增一条评论,该字段值加 1,查询的时候直接取该字段即可,从而提高查询的性能。
尝试将with()函数与联接一起使用时遇到问题:$query = Model::query()->with([ 'relationOne', 'relationTwo', ...]);$query->join(DB::raw("( select * from <models_table> where <some_condition>) as new_model"), 'new_model.id', '=', '<models_table>.id');$query->paginate($rpp);...
use Illuminate\Database\Eloquent\Relations\Relation; Relation::morphMap([ 'posts' => 'App\Post', 'videos' => 'App\Video', ]); 你可以在 AppServiceProvider 的boot 方法中注册这个 morphMap,如果需要的话,也可以创建一个独立的服务提供者来实现这一功能。
use Illuminate\Database\Eloquent\Relations\Relation; Relation::morphMap([ 'posts' => 'App\Post', 'videos' => 'App\Video', ]);可以在 AppServiceProvider 的boot 函数中注册 morphMap,或者创建一个单独的服务提供者。查询关联由于Eloquent 关联的所有类型都通过方法定义,你可以调用这些方法,而无需真实...
Relation::morphMap([ 'posts' => App\Post::class, 'likes' => App\Like::class, ]);译者注:可以使用 class_basename(App\Post::class) 来得到 Post你可以在 AppServiceProvider 中注册你的「多态对照表」,或是创建一个单独的提供者文件。多态多对多关联#...
如果你想要從關聯中計算結果的數字,而不載入它們。你可以使用 withCount 方法,該方法會在你的結果模型上放置 {relation}_count 欄位。例如:$posts = App\Post::withCount('comments')->get(); foreach ($posts as $post) { echo $post->comments_count; }Copy你可以為多個關聯新增「counts」,還有為查詢...
Defining a morph map provides support for eager loading and resolves additional bugs with polymorphic relations. If you were previously relying on the $morphClass property, you should migrate to morphMap using the following syntax:Relation::morphMap([ 'YourCustomMorphName' => YourModel::class, ]...
php withCount 方法将在生成的模型中放置一个 php {relation}_count 属性:use App\Models\Post; $posts = Post::withCount('comments')->get(); foreach ($posts as $post) { echo $post->comments_count; }通过将数组传递给 withCount 方法,你可以同时添加多个关系的 “计数”,并向查询添加其他约束:...