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,查询的时候直接取该字段即可,从而提高查询的性能。
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...
use Illuminate\Database\Eloquent\Relations\Relation; Relation::morphMap([ 'posts' => 'App\Post', 'videos' => 'App\Video', ]); 你可以在 AppServiceProvider 的boot 方法中注册这个 morphMap,如果需要的话,也可以创建一个独立的服务提供者来实现这一功能。
如果你想要從關聯中計算結果的數字,而不載入它們。你可以使用 withCount 方法,該方法會在你的結果模型上放置 {relation}_count 欄位。例如:$posts = App\Post::withCount('comments')->get(); foreach ($posts as $post) { echo $post->comments_count; }Copy你可以為多個關聯新增「counts」,還有為查詢...
use Illuminate\Database\Eloquent\Relations\Relation; Relation::morphMap([ 'posts' => 'App\Post', 'videos' => 'App\Video', ]);可以在 AppServiceProvider 的boot 函数中注册 morphMap,或者创建一个单独的服务提供者。注意:在现有应用程序中添加「morph 映射」时,数据库中仍包含完全限定类的每个可变形 ...
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....
如果你想对关联数据进行计数但又不想再发起单独的 SQL 请求,你可以使用 withCount 方法,此方法会在你的结果集中增加一个 {relation}_count 字段:$posts = App\Post::withCount('comments')->get(); foreach ($posts as $post) { echo $post->comments_count; }...
$users = AppUser::with(["posts" => function ($query) { $query->orderBy("created_at", "desc");}])->get(); 延迟预加载 有时候你可能需要在上层模型被获取后才预加载其关联。当你需要来动态决定是否加载关联模型时尤其有用: $books = AppBook::all();if ($someCondition) { $books->load("...