简体   繁体   English

如何从table1中获取所有内容并通过laravel eloquent在单个查询中附加table2中的行数

[英]How to fetch all from table1 and attach count of rows from table2 in a single query by laravel eloquent

I'm using Laravel 5.8, and I have 2 tables in a (one-to-many) relationship as below: 我正在使用Laravel 5.8,我有一个(一对多)关系中的2个表,如下所示:

Contacts DB 联系人DB

  • id ID
  • name 名称
  • number

Send DB 发送数据库

  • id ID
  • user_id 用户身份
  • text 文本
  • to
  • time 时间

what I want to achieve is a list of all (Contacts) along with how many (send) they've made that related to that (contact) by matching Contacts.id with Send.user_id, 通过将Contacts.id与Send.user_id匹配,我想要实现的是所有(联系人)的列表以及他们与该(联系人)相关的多少(发送),

here is the result of the query that I'm looking for: 这是我正在寻找的查询的结果:

Query result: 查询结果:

  • id ID
  • name 名称
  • number
  • count of Sends 发送次数

Thank you :) 谢谢 :)

You need to setup your model relationship 您需要设置模型关系

Add the following to your Contact Model: 将以下内容添加到您的Contact模型:

public function sends()
{
    return $this->hasMany('App\Send', 'user_id'); //Assuming Send Model is directly in app folder
}

Then simply get your information: 然后只需获取您的信息:

$contact = Contact::withCount('sends')->get();

Worked like charm! 像魅力一样工作! I did tweak it to make it return a signal (contact) 我确实调整它以使其返回信号(联系人)

Contact::where('id', $id)->withCount('sends')->get();

here is another way as ( Jonathan K ) suggested 这是( Jonathan K )建议的另一种方式

Contact::where('id', $id)->withCount('sends')->first();

Thanks, Jonathan K 谢谢Jonathan K.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM