doubiao7410 2016-05-10 18:44
浏览 5

Laravel很多很多

I have a laravel application and I have the following models

  1. Workshop
  2. WorkshopCategory

I have 3 tables,

  • workshops
  • workshop_categories
  • workshop_category_relation

I am trying to use eloquent to out put all my workshops, with the associated categories like the following:

{

"id":14,
"workshop_name":"First Workshop",
"description":"Located all over",
"categories": array: [
      0 => "wood"
      1 => "metal"
    ]

}

What would the best method be to achieve this? would I in my workshop model add the following:

public function categories()
    {
        return $this->belongsToMany('App\Workshopcategory', 'workshop_category_relation', 'workshop_id', 'category_id');
    }

I have added the above function to my workshop model and when I try output a workshop like the following:

$workshop = Workshop::FindOrFail(14);
return $workshop->categories(); 

I get the following error:

Object of class Illuminate\Database\Eloquent\Relations\BelongsToMany could not be converted to string

  • 写回答

2条回答 默认 最新

  • dounuo1881 2016-05-10 18:57
    关注

    I think you're just looking for a Many to Many relation.

    All you'll need to do is rename your workshop_category_relation table to 'workshop_category' and then your belongsToMany should work.

    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制