drde3456 2016-12-29 15:26
浏览 123
已采纳

使用laravel获取多个对象的关系

A User has many Phones. I want to get all the phones from active users. I can do:

$phones = [];
$users = User::with('phones')->where('active', 1)->get();
foreach($users as $user) {
    $phones = array_merge($phones, $user->phones->toArray());
}
dd($phones); // <- Here are all the phones.

But I'm not sure it's the more elegant or laravel-ish way. Is there a built in magic function for such a case? Can I get all the phones from active users without writing a loop and insert in an Array?

  • 写回答

2条回答 默认 最新

  • douye5949 2016-12-29 15:28
    关注

    You should use whereHas() method:

    $phones = Phone::whereHas('user', function($q) {
        $q->where('active', 1);
    })->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services