首页 文章

如何加入Eloquent?

提问于
浏览
0

从Laravel中的Eloquent模型中选择时,我想进行自动连接分组 .

我们假设我有这些表格:

humans        pets 
------        ----
int id        int id
varchar name  varchar name
              varchar category  
              int owner_id

填充了这些值:

humans        pets
------        ----
1 Bob         1 Lucy Dog 1
2 Alice       2 Sadie Dog 1 
3 Eve         3 Buster Cat 2
              4 Sam Fish 2

因此,在我的PHP中我有这些模型:

class Human extends Eloquent {
}

class Pet extends Eloquent {
}

这是我的愿望:

function wish() {
   return Human::all()->magic()->toJson();
}

为此,我希望得到这个确切的输出 . 我应该放什么 magic()

[
  {
    "id": 1,
    "name": "Bob",
    "pets": [
      {"id": 1, "name": "Lucy", "category": "Dog"},
      {"id": 2, "name": "Sadie", "category": "Dog"}
    ]
  },
  {
    "id": 1,
    "name": "Alice",
    "pets": [
      {"id": 3, "name": "Buster", "category": "Cat"},
      {"id": 4, "name": "Sam", "category": "Fish"}
    ]
  },
  {
    "id": 1,
    "name": "Eve",
    "pets": []
  }
]

1 回答

  • 0

    你的魔法分两步完成:

    class Human extends Eloquent {
        public function pets() 
        {
            return $this->hasMany('Pet');
        }
    }
    

    并为您的查询

    function wish() {
       return Human::with('pets')->all()->toJson();
    }
    

    您还可以在模型中包含 with

    class Human extends Eloquent {
        protected $with = ['pets'];
    
        public function pets() 
        {
            return $this->hasMany('Pet');
        }
    }
    

    有关此内容的文档可从此处获得:

    https://laravel.com/docs/5.7/eloquent-relationships

相关问题