publicfunctionbelongsToMany($related,$table=null,$foreignPivotKey=null,$relatedPivotKey=null,$parentKey=null,$relatedKey=null,$relation=null) 第一个参数是关联模型的类名。第二个参数是中间表,第三个参数是中间表中当前模型类的外键,第四个参数是中间表当前关联模型类的外键,第五个参数表示对应当前模型的哪...
如果要统计其它关联模型结果数量字段,可以依次类推,对应字段都是 {relation}_count 结构。 注:实际开发中为了提高查询性能,我们往往是在 posts 表中冗余提供一个 comments_count 字段,每新增一条评论,该字段值加 1,查询的时候直接取该字段即可,从而提高查询的性能。 此外,你还可以通过数组传递多个关联关系一次统计...
use Illuminate\Database\Eloquent\Relations\Relation; Relation::morphMap([ App\Post::class, App\Comment::class, ]); 或者,你可以指定一个自定的字符串与每个模型进行关联: use Illuminate\Database\Eloquent\Relations\Relation; Relation::morphMap([ 'posts' => App\Post::class, 'likes' => App\Like...
如果要统计其它关联模型结果数量字段,可以依次类推,对应字段都是 {relation}_count 结构。注:实际开发中为了提高查询性能,我们往往是在 posts 表中冗余提供一个 comments_count 字段,每新增一条评论,该字段值加 1,查询的时候直接取该字段即可,从而提高查询的性能。
use Illuminate\Database\Eloquent\Relations\Relation; Relation::morphMap([ 'posts' => 'App\Post', 'videos' => 'App\Video', ]); 你可以在 AppServiceProvider 的boot 方法中注册这个 morphMap,如果需要的话,也可以创建一个独立的服务提供者来实现这一功能。
如果你想对关联数据进行计数但又不想再发起单独的 SQL 请求,你可以使用 withCount 方法,此方法会在你的结果集中增加一个 {relation}_count 字段:$posts = App\Post::withCount('comments')->get(); foreach ($posts as $post) { echo $post->comments_count; }...
您可以在 AppServiceProvider 中的boot 函数中使用 Relation::morphMap 方法注册「多态映射表」,或者使用一个独立的服务提供者注册。多对多多态关联数据表结构除了传统的多态关联,您也可以定义「多对多」的多态关联。例如,Post 模型和 Video 模型可以共享一个多态关联至 Tag 模型。 使用多对多多态关联可以让...
the same two queries. The key difference is that with() eager loads the related model up front, immediately after the initial query (all(), first(), or find(x), for example); when using load(), you run the initial query first, and then eager load the relation at some later point....
或者是对应字段: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」,還有為查詢...