php - 如何将多个表与 Laravel 结合?

标签 php arrays laravel

例如;

 $hall_templates = HallTemplate::where('hall_id' , $id)->orderBy('order' , 'ASC')->get();

输出:

 [{"id":16,"hall_id":3,"template_name":"Magazin Outlet","order":1,"width":12,"height":12},
  {"id":17,"hall_id":3,"template_name":"Merinos K\u00fclt\u00fcr Merkezi","order":2,"width":22,"height":12}]

例如第二个表信息如下;

$armchair_number_count = HallTemplateArmChair::where('template_id' , 16)->get();

输出:

[{"id":1,"template_id":16,"armchair_no":"a1"}, 
 {"id":2,"template_id":16,"armchair_no":null}]

我怎样才能合并这两个表。 我想做输出:

array({"id":16,"hall_id":3,"template_name":"Magazin Outlet","order":1,"width":12,"height":12, "armchair_number_count",2},
{"id":17,"hall_id":3,"template_name":"Merinos K\u00fclt\u00fcr Merkezi","order":2,"width":22,"height":12, "armchair_number_count",0);

感谢您的帮助。

最佳答案

使用withCount()方法:

HallTemplate::withCount('armchairNumber')->where('hall_id' , $id)->orderBy('order' , 'ASC')->get();

此方法将对椅子进行计数,并向每个 HallTemplate 对象添加 armchair_number_count 属性。

要使其正常工作,请在 HallTemplate 模型中定义关系:

public function armchairNumber()
{
    return $this->hasMany(HallTemplateArmChair::class, 'template_id');
}

关于php - 如何将多个表与 Laravel 结合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48840082/

相关文章:

php - MySql 5.7 : General error: 1366 Incorrect integer value: '' for TinyInt(1) field

php - 调用非对象的成员函数 bindValue()。 PHP 版本不同?

ios - 如何将 UIImages 添加到我的 PFFile 数组中,以便在查询 PFFIle 图像失败时,可以通过附加 UIImage 来替换它?

javascript - laravel pdf文件从ajax请求下载(laravel 5)

php - 如何修复 "The GET method is not supported for this route. Supported methods: POST."

php - 在 php :7. 4-fpm 镜像上安装 PHP-zip

php - 搜索脚本不返回查询

php - 列出从 MySQL DB 到 PHP 站点的项目

Python如何以C速度循环遍历numpy中的数组并存储一些位置

php - print_r() 仅打印出数组中的 150 个元素