icemanpro
V2EX  ›  PHP

laravel 中如何得到一对多的关联模型中记录数量?

  •  
  •   icemanpro · Apr 18, 2016 · 8450 views
    This topic created in 3861 days ago, the information mentioned may be changed or developed.
    例如有 user 和 post 两个模型, user 和 post 是一对多关联,现想通过 user 模型得到对应 post 的数量,应该如何写?
    3 replies  •  2016-04-19 09:05:38 +08:00
    justk
    justk
    Apr 18, 2016
    1
    user->posts->count()
    magichan
    magichan
    Apr 18, 2016
    2
    Laravel 的 Eloquent 返回的都是一个 Illuminate\Database\Eloquent\Collection 对象的实例。包含很多有用的操作,你的问题通过 Collection 很用解决。
    http://7xozg1.com1.z0.glb.clouddn.com/2016-04-18%2019:08:04%20%E7%9A%84%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE.png
    xueyunlong67
    xueyunlong67
    Apr 19, 2016
    3
    Eloquent ORM 关联查询,最后对结果进行 count()
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2091 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 05:54 · PVG 13:54 · LAX 21:54 · JFK 00:54
    ♥ Do have faith in what you're doing.