Eloquent 加入 2 个表

Eloquent join 2 tables

我正在构建一个输出 json

的 api

所以我有 2 tables

Categories Table
    id
    name
    nameAR
    nameTR

Items table
    id
    category_id
    nameAR
    nameEN

我的 json 输出完全像这样,因为 android 应用程序已经发布并且此 API 将替换静态 json 文件

{
"name" : *Category name*,
"nameAR" : *Category Arabic name*,
"nameTR" : *Category Turkish name*,
"items" : [

   {"nameAR": *Item Arabic name*,
   "nameEN": *Item English name*},

   {"nameAR": *Item2 Arabic name*,
   "nameEN": *Item2 English name*}

   ... etc
   ]
}

我知道我可以做到:

$cat=Category::first();
$items=$cat->items;

获取单个变量中的每个 table 但我想要的是使用 Category::all() 获取所有类别并放入所有属于的项目作为类别对象

中名为 items 的数组中的对象添加到类别

*我确实配置了我的关系

Category : 
    public function items()
        {
          return $this->hasMany('Project\Item');
        }

Item: 
    public function category()
        {
          return $this->belongsTo('Project\Category');
        }

要获取包含属于您可能使用的那些类别的项目的所有类别:

$categories = Category::with('items')->get();

当将集合返回为 Json 时,您将得到您想要的,但您将有一些额外的列(如果您需要,您需要使用 select 来仅选择您真正需要的列)

使用地图功能

        $categories = Categorie::all();
        $categories->map(function ($cat){
            $cat->items=Item::where('category_id',$cat->id)->get();
        });