我如何将多个表与Laravel结合使用?

时间:2018-02-17 09:59:09

标签: 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);

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

使用withCount()方法:

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

此方法会计算主席数,并会为每个armchair_number_count对象添加HallTemplate属性。

要使其有效,请在HallTemplate模型中定义关系:

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