[英]How to fetch all from table1 and attach count of rows from table2 in a single query by laravel eloquent
我正在使用Laravel 5.8,我有一個(一對多)關系中的2個表,如下所示:
通過將Contacts.id與Send.user_id匹配,我想要實現的是所有(聯系人)的列表以及他們與該(聯系人)相關的多少(發送),
這是我正在尋找的查詢的結果:
謝謝 :)
您需要設置模型關系
將以下內容添加到您的Contact
模型:
public function sends()
{
return $this->hasMany('App\Send', 'user_id'); //Assuming Send Model is directly in app folder
}
然后只需獲取您的信息:
$contact = Contact::withCount('sends')->get();
像魅力一樣工作! 我確實調整它以使其返回信號(聯系人)
Contact::where('id', $id)->withCount('sends')->get();
這是( Jonathan K )建議的另一種方式
Contact::where('id', $id)->withCount('sends')->first();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.